尝试在python中处理字典列表时出错

时间:2014-08-28 03:40:47

标签: python list dictionary unicode encode

我在Python中有一个字典列表(包含单值和多值的键)。

显然,数据是unicode格式,这是我面临的问题。

x = "..." my list of dictionaries  #printing type(x) gave me "unicode"

我希望能够做到

for i in x:
    print i[key]

我认为这对unicode来说似乎不太直接。我做到了,

r = x.encode('utf8') # printing type(r) gave me "str"

但是当我做的时候

 for i in r: #r here is in str format
        print i[key]

我收到以下错误“TypeError:string indices必须是整数,而不是str”

非常令人困惑!

1 个答案:

答案 0 :(得分:1)

如果您的词典列表是问题中提到的字符串,那么请使用ast模块' literal_eval()将其转换为字典列表。然后,您可以访问字典中的键和值。

演示:

>>> import ast
>>> data = "[{'a':'b'}, {'a':'d'}, {'a':'f'}]"

>>> type(data)
<type 'str'>

>>> list_of_dicts = ast.literal_eval(data)
>>> type(list_of_dicts)
<type 'list'>

>>> key = 'a'
>>> for i in list_of_dicts:
...     print i[key]
...
b
d
f