Mirage
Mirage

Reputation: 31548

How can i change the values in dictionary of lists in python

I hae a dictionary like this

dict1 = [('var1','aa'),('var2','bb')('var3','cc')]

I have another dictionary

dict2 = [('var2','22'),('var3','33'),('var5','23'),('var6','33'),('var7','23')]

What i want to do is that i to replace the contents of dict2 with the varibels in dict1

I mean so that final dict3 = dict2 = [('var2','bb'),('var3','cc'),('var5','23'),('var6','33'),('var7','23')]

Upvotes: 0

Views: 111

Answers (2)

sberry
sberry

Reputation: 131978

>>> list1 = [('var1','aa'),('var2','bb'),('var3','cc')]
>>> list2 = [('var2','22'),('var3','33'),('var5','23'),('var6','33'),('var7','23')]
>>> dict1 = dict(list1)
>>> list2 = [(k, dict1.get(k, v)) for k, v in list2]
>>> list2
[('var2', 'bb'), ('var3', 'cc'), ('var5', '23'), ('var6', '33'), ('var7', '23')]

This will maintain order from the original list2

Upvotes: 5

Matthew Adams
Matthew Adams

Reputation: 10126

Those are not dictionaries. Here is how to do it if they were:

>>> dict1 = {'var1':'aa', 'var2':'bb' ,'var3':'cc'}
>>> dict2 = {'var2':'22', 'var3':'33', 'var5':'23', 'var6':'33', 'var7':'23'}
>>> for key in dict2:
...     if key in dict1:
...             dict2[key] = dict1[key]
... 
>>> dict2
{'var5': '23', 'var7': '23', 'var6': '33', 'var3': 'cc', 'var2': 'bb'}

You probably want to start out with dict1 and dict2 actually being dictionaries as in my example, but note that you can easily convert them using eg. dict1 = dict(dict1).

Upvotes: 3

Related Questions