salamey
salamey

Reputation: 3811

Adding a key value pair to a list of dicts based on another list Python

Sorry if the title is not clear, but here is what I'm trying to achieve.

I have a list of dicts :

l = [{'name': 'inAnalysis'}, {'name': 'inQuest'}, {'name': 'inDevelopment'}]

And a sort of translation table like this :

tr = {'inAnalysis' : 1, 'inDevelopment' : 2, 'inQuest' : 3}

I want to add the key value to l like this :

l = [{'name': 'inAnalysis', 'order' : 1},
     {'name': 'inQuest', 'order' : 3}, 
     {'name': 'inDevelopment', 'order' : 2}]

How can I match the value of l with the key of tr and get its value with the key order and add it to l? Any help would be appreciated. I'm using Python 2.6.

Upvotes: 1

Views: 1512

Answers (2)

three_pineapples
three_pineapples

Reputation: 11849

If you want to modify the existing dictionaries in place (note that thefoutheye's solution makes new dictionaries which could concievably be a problem if something else in your code is holding a reference to the dictionaries in the list, rather than the list itself) you can do:

for my_dict in l:
    my_dict['order'] = tr[my_dict['name']]

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239443

You can use list comprehension to dynamically generate the dictionaries like this

print [{"name":dic["name"], "order":tr[dic["name"]]} for dic in l]

Output

[{'name': 'inAnalysis', 'order': 1},
 {'name': 'inQuest', 'order': 3},
 {'name': 'inDevelopment', 'order': 2}]

Alternatively, you can use the following

for dic in l: dic["order"] = tr[dic["name"]]

this modifies the dictionaries in-place.

Upvotes: 5

Related Questions