Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I  want to create a method that will add each given key/value pair to the dictionary. The parameter named key_value_pairs will be a list of tuples in the form of (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 don't know how to update the "value" variable when d and key_value_pairs have different keys.

The first three of these situations work but the rest is not working:

>>> 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}

1 Answer

0 votes
by (108k points)
edited by

Kindly be informed that Python is having an in-built feature named update():

>>> d = {'b': 4}

>>> d.update({'a': 2})

>>> d

{'a': 2, 'b': 4}

You cannot use dict.update as it will not work in python 3x version:

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

If you want to learn python then do check out the below python tutorial video for better understanding:

Related questions

+1 vote
2 answers
asked Aug 19, 2019 in Python by nymeria96 (240 points)
0 votes
1 answer
asked Dec 5, 2020 in Python by laddulakshana (16.4k points)
0 votes
4 answers
0 votes
1 answer
asked Nov 26, 2020 in Python by ashely (50.2k points)

Browse Categories

...