二维数组/字典组合

时间:2014-02-10 21:38:40

标签: python arrays dictionary

有没有办法定义二维数组/字典组合,其中第一个值是枚举,第二个是关联?理想情况下,最终结果看起来像这样,第一个是简单索引,第二个是键 - >值对。

data[0]["Name"] = ...

提前致谢!

3 个答案:

答案 0 :(得分:5)

扩展我的评论list dict s:

>>> list_of_dicts = [{'first_name':'greg', 'last_name':'schlaepfer'},
...                  {'first_name':'michael', 'last_name':'lester'}]
>>>
>>> list_of_dicts[0]['first_name']
'greg'

答案 1 :(得分:0)

当然 - 词典列表:

>>> 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'

答案 2 :(得分:0)

dicts = [  {"name": "Tom", "age": 10 },
           {"name": "Tom", "age": 10 },
           {"name": "Tom", "age": 10 }  ]

print dicts[0]['name']

基本上,您将创建一个词典列表。作为评论提前获得正确答案的道具mhlester