有没有办法定义二维数组/字典组合,其中第一个值是枚举的,第二个值是关联的?理想情况下,最终结果如下所示,其中第一个是简单索引,第二个是键>值对。
data[0]["Name"] = ...
提前感谢!
扩展我的评论,dict
s list
:
>>> list_of_dicts = [{'first_name':'greg', 'last_name':'schlaepfer'},
... {'first_name':'michael', 'last_name':'lester'}]
>>>
>>> list_of_dicts[0]['first_name']
'greg'
dicts = [ {"name": "Tom", "age": 10 },
{"name": "Tom", "age": 10 },
{"name": "Tom", "age": 10 } ]
print dicts[0]['name']
从本质上讲,您将创建一个字典列表。支持mhlester之前有正确的答案作为评论。
当然 -- 字典列表:
>>> 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
请确保在字典上使用dict
方法,在列表中使用list
方法:
还行:
>>> 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'}]
不行:
>>> 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'