hanuma sachin
hanuma sachin

Reputation: 43

map keys in one python dictionary to the exact value of other dictionary

mydict={'f1':'stream','f2':'status','f3':'remarks'}

mydict1={'stream':'RHEL','status':'pass','remarks':'none'}

required output

result={'f1':'RHEL','f2':'pass','f3': 'none'}

def function(mydict, mydict1):
    for key,value in mydict1.iteritems():
        print mydict1[key]

Upvotes: 3

Views: 59

Answers (2)

Iron Fist
Iron Fist

Reputation: 10961

To fix your code, iterate through mydict.items() instead, and then append to result dictionary, this way:

>>> mydict={'f1':'stream','f2':'status','f3':'remarks'}
>>> mydict1={'stream':'RHEL','status':'pass','remarks':'none'}    
>>>def function(mydict, mydict1):
           for key,value in mydict.items():
               result[key] = mydict1[value]
           return result
>>>function(mydict, mydict1)
{'f1': 'RHEL', 'f2': 'pass', 'f3': 'none'}

Of course, this could be lot simplified as falsetru posted in his answer, using dictionary comprehension.

Upvotes: 1

falsetru
falsetru

Reputation: 369424

Using dictionary comprehension:

>>> mydict = {'f1': 'stream', 'f2': 'status', 'f3': 'remarks'}
>>> mydict1 = {'stream': 'RHEL', 'status': 'pass', 'remarks': 'none'}
>>> {key: mydict1[value] for key, value in mydict.items()}
{'f1': 'RHEL', 'f2': 'pass', 'f3': 'none'}

Upvotes: 2

Related Questions