3

Say I have two dictionaries:

animal = {
  "CA": "Grizzly Bear",
  "ID": "Appaloosa",
  "NY": 'Beaver'
}

flower = {
  "CA": "tulip",
  "ID": "syringa",
  "NY": 'rose'
}

How can I combine these two dictionaries into a nested dictionary with the level of state > animal/flower > value. Like the following:

dict3 = {'CA': {'animal':'Grizzly Bear','flower':'tulip'},
         'ID': {'animal':'Appaloosa','flower':'syringa'},
         'NY': {'animal':'Beaver','flower':'rose'}}
print(dict3)

The code above works manually but I want to know a more efficient way to to this with any amount of states. I imagine I would rearrange the key/values with loops but I am wondering if there is an efficient way.

Thanks!

user2390182
  • 72,016
  • 6
  • 67
  • 89
jhwaffles
  • 31
  • 3

3 Answers3

4

You can use this dict comprehension, which intersects the keys:

>>> {k: {'animal': animal[k], 'flower': flower[k]} for k in animal.keys() & flower.keys()}
{'CA': {'animal': 'Grizzly Bear', 'flower': 'tulip'}, 'NY': {'animal': 'Beaver', 'flower': 'rose'}, 'ID': {'animal': 'Appaloosa', 'flower': 'syringa'}}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
3

Try this:

animal = { "CA": "Grizzly Bear", "ID": "Appaloosa", "NY": 'Beaver' }

flower = { "CA": "tulip", "ID": "syringa", "NY": 'rose' }

dict3 = { }
for k in animal.keys() & flower.keys():
    dict3[k] = {"animal":animal[k], "flower":flower[k]}

print(dict3)

Or

The best (Pythonic) way is by using dict comprehension:

print({k:{"animal":animal[k], "flower":flower[k]} for k in animal.keys() & flower.keys()})

Output:

{'CA': {'animal': 'Grizzly Bear', 'flower': 'tulip'}, 'ID': {'animal': 'Appaloosa', 'flower': 'syringa'}, 'NY': {'animal': 'Beaver', 'flower': 'rose'}}

NOTE:

I have used & to get an intersections of keys in the two dictionaries. Using this, we make sure we use keys (for making our new dict) that are present in both the dicts (Otherwise, you may get KeyError).

abhiarora
  • 9,743
  • 5
  • 32
  • 57
0

It seems the most efficient way is

keys = set(animal.keys()).update(flower.keys())
dict3 = {key: dict(animal=animal.get(key), flower=flower.get(key))
         for key in keys}

It works for O(N), where N is the sum of sizes of your dicts.

Also notice how this handles the case of a missing flower or a missing animal: the dict will hold None. This may or may not be what you want depending on your use case.

kreo
  • 2,613
  • 2
  • 19
  • 31