user2921139
user2921139

Reputation: 1789

Error while trying to process a list of dictionaries in python

I have a list of dictionaries (key with both single and multiple values) in Python.

Apparently, the data is in unicode format which is the issue i m facing.

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

I want to be able to do

for i in x:
    print i[key]

This does not seem straight forward with the unicode i guess. So i did,

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

but when i do

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

I get the following error "TypeError: string indices must be integers, not str"

It is very confusing!

Upvotes: 0

Views: 1113

Answers (1)

shaktimaan
shaktimaan

Reputation: 12092

If your list of dictionaries is a string as you mentioned in the question, then use ast modules' literal_eval() to convert it into a list of dictionaries. Then you can access the keys and values in the dictionary.

Demo:

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

Upvotes: 1

Related Questions