如何访问词典列表中的值

时间:2014-06-26 19:52:23

标签: python list dictionary

我有以下词典列表:

d =  [(u'Code', u'US'), (u'Country', u'United States'), (u'Name', u'Bill')]

如何访问各个词典的值?

eg. d['Code'] gives 'US' - obviously does not work

1 个答案:

答案 0 :(得分:6)

这不是词典列表;它是两项元组的列表:

>>> d =  [(u'Code', u'US'), (u'Country', u'United States'), (u'Name', u'Bill')]
>>> type(d)
<class 'list'>
>>> type(d[0])
<class 'tuple'>
>>>

如果您想将d转换为字典,请将其放入dict

>>> d =  [(u'Code', u'US'), (u'Country', u'United States'), (u'Name', u'Bill')]
>>> d = dict(d)
>>> d
{'Code': 'US', 'Name': 'Bill', 'Country': 'United States'}
>>> d['Code']
'US'
>>>