-5

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?

Nik
  • 5,515
  • 14
  • 49
  • 75
  • 2
    this is not a dict, as you do not have keys in your structure, maybe you meant list of dicts? – lejlot Jun 22 '16 at 23:08
  • 1
    There is a way to use dict-comprehension inside of a list-comprehension, yes, but could you show what you've tried? – OneCricketeer Jun 22 '16 at 23:09
  • Why do you want multiple dictionaries with `{'name':name, 'age':age}` instead of a single dictionary of `{name:age, name:age...}`? – TigerhawkT3 Jun 22 '16 at 23:33
  • @TigerhawkT3: the resulting structure would go as input to another module which needed the dictionary structure to be what I described above. The other module is not editable. – Nik Jun 22 '16 at 23:39

3 Answers3

4

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.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
3

That would be a list of dictionaries, since each entry has to have a key in order for the whole thing to be a dictionary.

You can make one with a dictionary inside a list comprehension like this:

[{'name': name, 'age': age} for name, age in l]

Also note that while dictionaries themselves are unordered, this list of dictionaries will preserve the order of the list l.

Dmiters
  • 2,011
  • 3
  • 23
  • 31
2

you can make a function to do it

def list2dict(list_):
    changed=[{'name':i[0],'age':i[1]} for i in list_]
    return changed

then just call

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

Tested in python 3.4.4