fransua
fransua

Reputation: 533

How to match 2 dictionary in python with their keys?

Here are my 2 dictionaries :

dictName={5159:'Cube',1007455:'Subdivision Surface'}
dictObj={5159: 7,1007455: 2}

I would like to get as a result :

Cube : 7, Subdivision Surface : 2

I can't figure how to achieve that with their keys.

Upvotes: 0

Views: 57

Answers (3)

Freakazoid
Freakazoid

Reputation: 520

Its faster and easyer with list comprehension:

solution = {dictName[key_name]:dictObj[key_obj]
            for key_name in dictName.keys() for key_obj in dictObj.keys()
            if key_name == key_obj}

Update: You need to check same names as well hence, the double list comprehension.

Upvotes: 0

firefrorefiddle
firefrorefiddle

Reputation: 3805

>>> for k,v in dictName.iteritems():                                                                                                                                          
...    result[v] = dictObj[k]                                                                                                                                                    
...                                                                                                                                                                              
>>> result                                                                                                                                                                       
{'Cube': 7, 'Subdivision Surface': 2}                                                                                                                                            
>>>                                             

Upvotes: 1

Nordle
Nordle

Reputation: 2981

You could do something like this:

dictName={5159:'Cube',1007455:'Subdivision Surface'}
dictObj={5159: 7,1007455: 2}

for k, v in dictName.items():
  if k in dictObj:
    print(f'{dictName[k]}: {dictObj[k]}')

and for Python 2 (after reading the question):

dictName={5159:'Cube',1007455:'Subdivision Surface'}
dictObj={5159: 7,1007455: 2}

for k, v in dictName.iteritems():
  if k in dictObj:
    print '%s : %s' % (dictName[k], dictObj[k])

..which will also catch any problems where the key is not mutual in both dictionaries.

Upvotes: 0

Related Questions