Back

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

I've been stuck on this inquiry for at some point and can't sort it out. I simply need to have the option to comprehend what I'm missing and why it's required. What I need to do is make a capacity that adds each given key/value pair to the word reference/dictionary. The contention key_value_pairs will be a list of tuples in the structure (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 sort out some way to refresh/update the "value" variable when d and key_value_pairs have various keys.

The initial three of these situations work yet the rest come up short

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

1 Answer

0 votes
by (26.4k points)

In python, We have a in-built feature

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

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

>>> d

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

Or on the other hand, given you're not permitted to utilize dict.update:

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

Want to learn python to get expertise in the concepts of python? Join python certification course and get certified

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...