Updating a Dictionary in Python

Updating a Dictionary in Python

I've been stuck on this question for quite sometime and just can't figure it out. I just want to be able to understand what I'm missing and why it's needed. What I need to do is make a function which adds each given key/value pair to the dictionary. The argument key_value_pairs will be a list of tuples in the form (key, value).

def add_to_dict(d, key_value_pairs):

    newinputs = [] #creates new list
    for key, value in key_value_pairs:
        d[key] = value #updates element of key with value
        if key in key_value_pairs:
            newinputs.append((d[key], value)) #adds d[key and value to list
    return newinputs

I can't figure out how to update the "value" variable when d and key_value_pairs have different keys.

The first three of these scenarios work but the rest fail

>>> d = {}
>>> add_to_dict(d, [])
[]
>>> d
{}

>>> d = {}
>>> add_to_dict(d, [('a', 2])
[]
>>> d
{'a': 2}

>>> d = {'b': 4}
>>> add_to_dict(d, [('a', 2)])
[]
>>> d
{'a':2, 'b':4}

>>> d = {'a': 0}
>>> add_to_dict(d, [('a', 2)])
[('a', 0)]
>>> d
{'a':2}

>>> d = {'a', 0, 'b': 1}
>>> add_to_dict(d, [('a', 2), ('b': 4)])
[('a', 2), ('b': 1)]
>>> d
{'a': 2, 'b': 4}

>>> d = {'a': 0}
>>> add_to_dict(d, [('a', 1), ('a': 2)])
[('a', 0), ('a':1)]
>>> d
{'a': 2}

Thanks

Edited.

7

7 Answers

Python has this feature built-in:

>>> d = {'b': 4}
>>> d.update({'a': 2})
>>> d
{'a': 2, 'b': 4}

Or given you're not allowed to use dict.update:

>>> d = dict(d.items() + {'a': 2}.items())   # doesn't work in python 3
4

With python 3.9 you can use an |= update operator:

>>> d = {'b': 4}
>>> d |= {'a': 2}
>>> d
{'a': 2, 'b': 4}

Here's a more elegant solution, compared to Eric's 2nd snippet

>>> a = {'a' : 1, 'b' : 2}
>>> b = {'a' : 2, 'c' : 3}
>>> c = dict(a, **b)
>>> a
{'a': 1, 'b': 2}
>>> b
{'a': 2, 'c': 3}
>>> c
{'a': 2, 'b': 2, 'c': 3}

It works both in Python 2 and 3

And of course, the update method

>>> a
{'a': 1, 'b': 2}
>>> b
{'a': 2, 'c': 3}
>>> a.update(b)
>>> a
{'a': 2, 'b': 2, 'c': 3}

However, be careful with the latter, as might cause you issues in case of misuse like here

>>> a = {'a' : 1, 'b' : 2}
>>> b = {'a' : 2, 'c' : 3}
>>> c = a
>>> c.update(b)
>>> a
{'a': 2, 'b': 2, 'c': 3}
>>> b
{'a': 2, 'c': 3}
>>> c
{'a': 2, 'b': 2, 'c': 3}

The new version of Python3.9 introduces two new operators for dictionaries: union (|) and in-place union (|=). You can use | to merge two dictionaries, while |= will update a dictionary in place. Let's consider 2 dictionaries d1 and d2

d1 = {"name": "Arun", "height": 170}
d2 = {"age": 21, "height": 170}
d3 = d1 | d2 # d3 is the union of d1 and d2
print(d3)

Output:

{'name': 'Arun', 'height': 170, 'age': 21}

Update d1 with d2

d1 |= d2
print(d1)

Output:

{'name': 'Arun', 'height': 170, 'age': 21}

You can update d1 with a new key weight as

d1 |= {"weight": 80}
print(d1)

Output:

{'name': 'Arun', 'height': 170, 'age': 21, 'weight': 80}

So if I understand you correctly you want to return a list of of tuples with (key, old_value) for the keys that were replaced.

You have to save the old value before you replace it:

def add_to_dict(d, key_value_pairs):

    newinputs = [] #creates new list
    for key, value in key_value_pairs:
        if key in d:
            newinputs.append((key, d[key]))
        d[key] = value #updates element of key with value
    return newinputs

Each key in a python dict corresponds to exactly one value. The cases where d and key_value_pairs have different keys are not the same elements.

Is newinputs supposed to contain the key/value pairs that were previously not present in d? If so:

def add_to_dict(d, key_value_pairs):
  newinputs = []
  for key, value in key_value_pairs:
    if key not in d:
      newinputs.append((key, value))
    d[key] = value
  return newinputs

Is newinputs supposed to contain the key/value pairs where the key was present in d and then changed? If so:

def add_to_dict(d, key_value_pairs):
  newinputs = []
  for key, value in key_value_pairs:
    if key in d:
      newinputs.append((key, value))
    d[key] = value
  return newinputs

If I understand you correctly, you only want to add the keys that do not exist in the dictionary. Here is the code:

def add_to_dict(d, key_value_pairs):
    newinputs = [];
    for key, value in key_value_pairs:
        if key not in d.keys():
            d[key] = value
            newinputs.append((key, value));
    return newinputs

For each key in new key,value pairs list you have to check if the key is new to the dictionary and add it only then. Hope it helps ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.