jumpman8947
jumpman8947

Reputation: 279

Combine two dictionaries with the same keys but different value types

I have two dictionaries, each with the same key, but different values.

food = {'fruit' : 5, 'vegetable' : 2, 'dairy' : 1, 'meat' : 3, 'grain' : 1}

fav = { 'fruit' : ['apple', 'orange', 'banana', 'grape', 'plum'],
        'vegetable' : ['carrot', 'corn'],
        'dairy' : ['milk'],
        'meat' : ['chicken', 'egg', 'beef'],
        'grain' : ['bread']
      }

The result I'm looking to achieve will be something like this,

eats = { 'fruit' : 5, ['apple', 'orange', 'banana', 'grape', 'plum'], 
         'vegetable' : 2, ['carrot', 'corn'],
       ...

etc etc.

***** EDIT ********

Also Some entries in each dictionary may be empty, for example

food = {'fruit' : 5, 'vegetable' : 2, 'dairy' : 1, 'meat' : 3, 'grain' : 1, 'sweets' : 0}

Sweets is not in fav, so how can i combine these dictionaries keeping sweets, and not getting a key error?

Upvotes: 1

Views: 680

Answers (3)

Anton Protopopov
Anton Protopopov

Reputation: 31672

You could use dict comprehension and tuples. I think you couldn't get the output you expecting because it's not valid dict (with comma should be separated neihbor keys):

eats = {key : (food[key],fav[key]) for key in food}

print(eats)
{'dairy': (1, ['milk']),
 'fruit': (5, ['apple', 'orange', 'banana', 'grape', 'plum']),
 'grain': (1, ['bread']),
 'meat': (3, ['chicken', 'egg', 'beef']),
 'vegetable': (2, ['carrot', 'corn'])}

EDIT

For your edit you need to add check key in fav dict:

eats = {key : (food[key],fav[key]) for key in food if key in fav}

The result for your example is the same as posted.

Upvotes: 5

Hackaholic
Hackaholic

Reputation: 19733

you can use Dictionary Comprehension:

>>> {key:[val, fav[key]] for key,val in food.items()}
{'vegetable': [2, ['carrot', 'corn']], 'dairy': [1, ['milk']], 'fruit': [5, ['apple', 'orange', 'banana', 'grape', 'plum']], 'grain': [1, ['bread']], 'meat': [3, ['chicken', 'egg', 'beef']]}

Upvotes: 0

liushuaikobe
liushuaikobe

Reputation: 2190

for key in food:
    eats[key] = [food[key], fav.get(key, [])]

Or, just one line,

eats = map(lambda x: [food[x], fav.get(x, [])], food.keys())

Upvotes: 0

Related Questions