Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
Kanade Swag Avatar asked Apr 17 '15 09:04

Kanade Swag


1 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
like image 71
Eric Avatar answered Oct 21 '22 09:10

Eric