Reputation: 25
Is there a way to define a two-dimensional array/dictionary combination, wherein the first value is enumerative and the second associative? The end result would ideally look like this, where the first is a simple index, and the second a key->value pair.
data[0]["Name"] = ...
Thanks in advance!
Upvotes: 1
Views: 7242
Reputation: 103874
Sure -- a list of dictionaries:
>>> LoD=[{c:i for i,c in enumerate(li)} for li in ('abc','def','ghi')]
>>> LoD
[{'c': 2, 'b': 1, 'a': 0}, {'f': 2, 'e': 1, 'd': 0}, {'g': 0, 'i': 2, 'h': 1}]
>>> LoD[2]['g']
0
>>> LoD[2]['h']
1
Be sure that you use dict
methods on the dicts and list
methods on the lists:
OK:
>>> LoD[2]['new']='new value'
>>> LoD
[{'c': 2, 'b': 1, 'a': 0}, {'f': 2, 'e': 1, 'd': 0}, {'g': 0, 'new': 'new value', 'i': 2, 'h': 1}]
>>> LoD.append({'new key':'new value'})
>>> LoD
[{'c': 2, 'b': 1, 'a': 0}, {'f': 2, 'e': 1, 'd': 0}, {'g': 0, 'new': 'new value', 'i': 2, 'h': 1}, {'new key': 'new value'}]
No go:
>>> LoD['new']='test'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> LoD[2].append('something')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'
Upvotes: 0
Reputation: 1037
dicts = [ {"name": "Tom", "age": 10 },
{"name": "Tom", "age": 10 },
{"name": "Tom", "age": 10 } ]
print dicts[0]['name']
Essentially, you would be creating a list of dictionaries. Props to mhlester for having the right answer earlier as a comment.
Upvotes: 0
Reputation: 23231
Expanding my comment, a list
of dict
s:
>>> list_of_dicts = [{'first_name':'greg', 'last_name':'schlaepfer'},
... {'first_name':'michael', 'last_name':'lester'}]
>>>
>>> list_of_dicts[0]['first_name']
'greg'
Upvotes: 5