Python: can I have a list with named indices?
In PHP I can name my array indices so that I may have something like:
$shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
Is this possible in Python?
Asked by: Walter823 | Posted: 28-01-2022
Answer 1
This sounds like the PHP array using named indices is very similar to a python dict:
shows = [
{"id": 1, "name": "Sesaeme Street"},
{"id": 2, "name": "Dora The Explorer"},
]
See http://docs.python.org/tutorial/datastructures.html#dictionaries for more on this.
Answered by: Kelvin359 | Posted: 01-03-2022Answer 2
PHP arrays are actually maps, which is equivalent to dicts in Python.
Thus, this is the Python equivalent:
showlist = [{'id':1, 'name':'Sesaeme Street'}, {'id':2, 'name':'Dora the Explorer'}]
Sorting example:
from operator import attrgetter
showlist.sort(key=attrgetter('id'))
BUT! With the example you provided, a simpler datastructure would be better:
shows = {1: 'Sesame Street', 2:'Dora the Explorer'}
Answered by: Emily240 | Posted: 01-03-2022
Answer 3
@Unkwntech,
What you want is available in the just-released Python 2.6 in the form of named tuples. They allow you to do this:
import collections
person = collections.namedtuple('Person', 'id name age')
me = person(id=1, age=1e15, name='Dan')
you = person(2, 'Somebody', 31.4159)
assert me.age == me[2] # can access fields by either name or position
Answered by: Sawyer306 | Posted: 01-03-2022
Answer 4
Yes,
a = {"id": 1, "name":"Sesame Street"}
Answered by: Walter279 | Posted: 01-03-2022
Answer 5
The pandas
library has a really neat solution: Series
.
book = pandas.Series( ['Introduction to python', 'Someone', 359, 10],
index=['Title', 'Author', 'Number of pages', 'Price'])
print book['Author']
For more information check it's documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html.
Answered by: Aida395 | Posted: 01-03-2022Answer 6
I think what you are asking is about python dictionaries.There you can named your indices as you wish . For ex:
dictionary = {"name": "python", "age": 12}
Answered by: Gianna863 | Posted: 01-03-2022
Answer 7
Python has lists and dicts as 2 separate data structures. PHP mixes both into one. You should use dicts in this case.
Answered by: Chester968 | Posted: 01-03-2022Answer 8
I did it like this:
def MyStruct(item1=0, item2=0, item3=0):
"""Return a new Position tuple."""
class MyStruct(tuple):
@property
def item1(self):
return self[0]
@property
def item2(self):
return self[1]
@property
def item3(self):
return self[2]
try:
# case where first argument a 3-tuple
return MyStruct(item1)
except:
return MyStruct((item1, item2, item3))
I did it also a bit more complicate with list instead of tuple, but I had override the setter as well as the getter.
Anyways this allows:
a = MyStruct(1,2,3)
print a[0]==a.item1
Answered by: Lenny472 | Posted: 01-03-2022
Similar questions
arrays - Python: Too many indices
I am trying to select amounts from an array given a criteria and reject the other amounts that do not fit. The criteria is: if amount[i,:]> x*amount[i-1,:] keep, otherwise keep prior amount. just like a treshold basically. And I am filling all these amount selected within a new array Array1. In the end the curve array takes it all and draws a curve. Now, the curve somehow always give me the same curve no matter what tresho...
Python: list indices must be integer, not str, when loading str array
I'm trying to load a big multidimensional array, first with strings (because stuff like 08 and 09 are registered as different type tokens) and then mapping them to integers.
strarray = [['08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08']
['49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00']
['81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65']
...
arrays - Python: Too many indices
I am trying to select amounts from an array given a criteria and reject the other amounts that do not fit. The criteria is: if amount[i,:]> x*amount[i-1,:] keep, otherwise keep prior amount. just like a treshold basically. And I am filling all these amount selected within a new array Array1. In the end the curve array takes it all and draws a curve. Now, the curve somehow always give me the same curve no matter what tresho...
Python: Find indices of the *first* match between two arrays
I'm trying to compare two arrays starting at the zeroth index to find the first time any element in arrayA matches any element in arrayB - and corresponding positions within each array.
The issue is, the code I've written is matching the last instance of matched elements - I'm not quite sure why.
Here's my code:
for a in arrayA:
for b in arrayB:
if ...
pandas - Python: how to map ID to matrix indices?
I have to convert an a number ID to index i and j of a matrix M of which I know the dimension. The expression is the following:
s = shape(M)
j = (ID - 1) % s[0]
i = np.int((ID - 1 - j) / s[0])
I have to save values coming from a dataframe df and each type I repeat the following:
M = np.zeros((m, n))
s = shape(...
python: handle out of range numpy indices
I am using the following code to rotate an image along it's y-axis.
y, x = np.indices(im1.shape[:2])
return im1[y, ((x-im1.shape[1]/2)/math.cos(t*math.pi/2)+im1.shape[1]/2).astype(np.int)]
Some of the values are intentionally out-of-range. I would like for out of range pixels to be black (0, 0, 0). How can I allow the in range indices to work, while replacing the out-of range with black?...
Python: use numpy array of indices to "lookup" values from another matrix
What is the fastest way of creating a new matrix that is a result of a "look-up" of some numpy matrix X (using an array of indices to be looked up in matrix X)? Example of what I want to achieve:
indices = np.array([[[1,1],[1,1],[3,3]],[[1,1],[5,8],[6,9]]]) #[i,j]
new_matrix = lookup(X, use=indices)
Output will be something like:
new_matrix = np.array([[3,3,7],[3,4,9...
Python: Array with too many Indices?
I'm trying to understand the code below and what it does:
im = pilimage.open(img_path)
image_array = np.array(im)
imgstack = image_array[area[0]:area[1],
area[2]:area[3], z_stack[0]:z_stack[1]]
I know that it opens up an image and stores it in im and then converts im into an array and stores that in image_array. What I don't rea...
pandas - Python: Work on the subset of a data over a common indices
I have a pandas dataframe
df1
Out[85]:
X0 X1 ... X14
2011-01-03 NaN NaN ... NaN NaN
2011-01-04 0.125194 1.125131 ... NaN NaN
2011-01-05 0.399821 -0.131389 ... NaN NaN
2011-01-06 1.019407 0.499459 ... NaN NaN
...
Python: Create an array using values and indices of a given array
Given the following list (or numpy array):
x = [4, 3, 1, 2]
I want to generate another list (or numpy array) with 1+4+3+2=10 elements such as:
y = [1, 1, 1, 1, 2, 2, 2, 3, 4, 4]
Where y will have x[i] successive elements with a value of i.
Other examples:
x = [0,3,1]
y = [2,2,2,3]
x = [2,0,2]
y = [1...
module - Python: import the containing package
In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function?
Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different ...
Python: Do Python Lists keep a count for len() or does it count for each call?
If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?
xml - Python: Using minidom to search for nodes with a certain text
I am currently faced with XML that looks like this:
<ID>345754</ID>
This is contained within a hierarchy. I have parsed the xml, and wish to find the ID node by searching on "345754".
Python: load words from file into a set
I have a simple text file with several thousands of words, each in its own line, e.g.
aardvark
hello
piper
I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose):
my_set = set(open('filename.txt'))
The above code produces a set with the following entries (each word is follow...
Python: Reading part of a text file
HI all
I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following:
<word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/>
I need the form, lemma and postag information. e.g. for above I need hibernis, hibernus1 and
python: can I extend the upper bound of the range() method?
What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:
for i in range(1,600851475143):
Python: better way to open lots of sockets
I have the following program to open lot's of sockets, and hold them open to stress test one of our servers. There are several problem's with this. I think it could be a lot more efficient than a recursive call, and it's really still opening sockets in a serial fashion rather than parallel fashion. I realize there are tools like ab that could probably simulate what I'm trying to do, but I'm hoping to increase my python ...
Python: Get Mount Point on Windows or Linux
I need a function to determine if a directory is a mount point for a drive.
I found this code already which works well for linux:
def getmount(path):
path = os.path.abspath(path)
while path != os.path.sep:
if os.path.ismount(path):
return path
path = os.path.abspath(os.path.join(path, os.pardir))
return path
But I'm not sure how I would get this to work on windows. Can ...
Python: remove lots of items from a list
I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.
I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.
So, I might have
myList = [(20000, 11), (16000, 4), (14000, 9)...
url - Python: Grab the A record of any URI?
I basically want to implement something where you can type in any URI ( I probably will only deal with http ) and I want to return the A record of the domain in the URI, I want the server's IP address.
I know there's the ping command which most people use to look an ip address up, but I also know there's 'host' and 'dig' which are more specific.
Are there any native functions I can use that will do this f...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python