0

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')]

Matthew Adams
  • 9,426
  • 3
  • 27
  • 43
Mirage
  • 30,868
  • 62
  • 166
  • 261
  • 9
    those aren't dictionaries, they are lists of tuples, convert them to dictionaries with dict(), iterate through the keys and replace. – monkut Dec 10 '12 at 06:07
  • @monkut Why didn't you post that as an answer? You beat me to the punch (while I was writing out code). – Matthew Adams Dec 10 '12 at 06:20

2 Answers2

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

sberry
  • 128,281
  • 18
  • 138
  • 165
  • @user33 Well proves me wrong haha. However, if you are "replacing" the values associated with variables like that, you really should be using a dictionary. Tuples are immutable, and dictionaries are meant for (seemingly) exactly what you are doing. – Matthew Adams Dec 10 '12 at 06:23
  • @Mathew Actually my other bit code is using the tuple. Initially i didn't need to chnage it. but now i need to make few replacements. so i just prefered as end result be tuple so that i don't need to touch the rest of code. i am new to python so was confsued with dic and tuple. i just wanted to replace the things, didn't knew if thats dict or tuple. Your solution is also good but this is just what i wanted. As i have written in your comment before i saw this answer – Mirage Dec 10 '12 at 06:29
  • @user33 I'm just trying to explain why, in the future, you want to use a dictionary for things like this. [Another explanation](http://stackoverflow.com/questions/3649841/what-are-differences-between-list-dictionary-and-tuple-in-python). – Matthew Adams Dec 10 '12 at 06:34
3

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

Matthew Adams
  • 9,426
  • 3
  • 27
  • 43