user479870
user479870

Reputation:

Merge nested dictionaries, by nested keys?

I have several dictionaries with different and common keys, plus different and common keys in the nested dictionary. Below is a simplified example, the actual dictionaries have thousands of keys.

{1:{"Title":"Chrome","Author":"Google","URL":"http://"}}
{1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}}
{2:{"Title":"Python","Version":"2.5"}}

Which I'd like to merge into a single dictionary.

{1:{"Title":"Chrome","Author":"Google","URL":"http://","Version":"7.0.577.0"},
 2:{"Title":"Python","Version":"2.5"}}

I can iterate over both dictionaries, compare keys and update the nested dictionaries, but there is probably a more efficient, or pythonic, way to do this. If not, which is the most efficient?

Values of the nested dictionary need not be compared.

Upvotes: 8

Views: 3400

Answers (4)

abduljalil
abduljalil

Reputation: 153

This approach is much faster

my_dicts = [   {1:{"Title":"Chrome","Author":"Google","URL":"http://"}},   {1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}},   {2:{"Title":"Python","Version":"2.5"}},]
result = {}
for d in my_dicts:
    for k, v in d.items():
        result.setdefault(k, {}).update(v)
print(result)

Upvotes: 0

edd313
edd313

Reputation: 1459

Try with a NestedDict. First install ndicts

pip install ndicts

Then

from ndicts.ndicts import NestedDict

my_dicts = [
   {1:{"Title":"Chrome","Author":"Google","URL":"http://"}},
   {1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}},
   {2:{"Title":"Python","Version":"2.5"}},
]
nd = NestedDict()

for my_dict in my_dicts:
    nd.update(NestedDict(my_dict))

To get the result as a dictionary

>>> nd.to_dict()
{1: {'Title': 'Chrome', 'Author': 'Google', 'Version': '7.0.577.0', 'URL': 'http://'}, 
 2: {'Title': 'Python', 'Version': '2.5'}}

Upvotes: 0

Thomas K
Thomas K

Reputation: 40340

From your example, looks like you can do something like:

from collections import defaultdict
mydict = defaultdict(dict)
for indict in listofdicts:
    k, v = indict.popitem()
    mydict[k].update(v)

Upvotes: 2

nosklo
nosklo

Reputation: 222852

from collections import defaultdict

mydicts = [
   {1:{"Title":"Chrome","Author":"Google","URL":"http://"}},
   {1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}},
   {2:{"Title":"Python","Version":"2.5"}},
]

result = defaultdict(dict)

for d in mydicts:
    for k, v in d.iteritems():
        result[k].update(v)

print result

defaultdict(<type 'dict'>, 
    {1: {'Version': '7.0.577.0', 'Title': 'Chrome', 
         'URL': 'http://', 'Author': 'Google'}, 
     2: {'Version': '2.5', 'Title': 'Python'}})

Upvotes: 6

Related Questions