Naoko Nishimura
Naoko Nishimura

Reputation: 87

insert dictionaries to a dictionary in Python

I have a dictionary like this:

dict1={'a':4,'d':2}

I have a list of dictionaries like this:

diclist=[{'b':3,'c':3},{'e':1,'f':1}]

As an output, I want to let dict1 be like this:

dict1={'a':4,'b':3,'c':3,'d':2,'e':1,'f':1}

so, I need to

  1. compare dict1's values with diclist's value
  2. if a value of a dict in diclist is smaller than the one of dict1, insert the dict to dict1
  3. iterate 2 in diclist

This might be easy, however, if you are willing to help with this, it'll be greatly appreciated.

Upvotes: 0

Views: 783

Answers (3)

John La Rooy
John La Rooy

Reputation: 304375

Since your keys in your example are all unique, how is it different from just merging all the dicts?

dict1 = {'a': 4, 'd': 2}
diclist = [{'b': 3, 'c': 3}, {'e': 1, 'f': 1}]
for d in diclist:
    dict1.update(d)

Here's a general approach. Consider providing more comprehensive examples in future

>>> dict1={'a':4,'d':2}
>>> diclist=[{'b':3,'c':3},{'e':1,'f':1}]
>>> 
>>> for d in diclist:
...  for k, v in d.items():
...   if k not in dict1 or v < dict1[k]:
...    dict1[k] = v
... 
>>> dict1
{'a': 4, 'c': 3, 'b': 3, 'e': 1, 'd': 2, 'f': 1}

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

Something like this:

In [15]: dict1={'a':4,'d':2}

In [16]: diclist=[{'b':3,'c':3},{'e':1,'f':1}]

In [17]: for dic in diclist:
    for key,value in dic.items():
        val=dict1.get(key,float("inf")) #fetch the value from dict1 if key is not found then return infinity
        if value < val:
            dict1[key] = value

In [18]: dict1
Out[18]: {'a': 4, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 1}

Upvotes: 0

John Jiang
John Jiang

Reputation: 11499

for d in diclist:  # iterate over the dicts
    for k, v in d.items():  # iterate over the elements
         v2 = dict1.set_default(k, v)  # set the value if the key does not exist
                                       # and return the value (existing or newly set)
         if v < v2:  # compare with the existing value and the new value
             dict1[k] = v

This is probably most concise and readable.

Upvotes: 0

Related Questions