Search code examples
pythonlistpython-2.7dictionarydict-comprehension

Python - convert list to dict


I have the following list:

l = [('Alice',12),('Bob',10),('Celine',11)]

I want to get the following dict (as correctly pointed in a comment below, this is not a dict. In reality, I just want a list of dicts):

[
    {'name':'Alice','age':12},
    {'name':'Bob','age':10},
    {'name':'Celine','age':11}
]

Is there a way I can use dict comprehension to achieve this?


Solution

  • You can create a list of dictionaries this way

    d = [{'name': x[0], 'age': x[1]} for x in l]
    

    Your example had a set/dictionary? of dictionaries which isn't really possible since dictionaries can't be hashed, and therefore can be used in sets or as dictionary keys.