简体   繁体   中英

I am having trouble with a python tutorial for updating dictionaries. I can't figure it out

It says: Write a function add_to_dict(d, key_value_pairs) where d is a dictionary to be updated and key_value_pairs is a list of tuples where [(key, value)].

It gives hints like: You can iterate over the pairs with, eg, for key, value in key_value_pairs.

You will need to build up a list using append.

It also gives examples of what should happen (inputs and outputs):

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}

As you have to return the old values. So modifying the @demented hedgehog's answer we get:

>>> def add_to_dict(d, kvlist):
...     out = []
...     for key, value in kvlist:
...         if key in d:
...            out.append((key, d[key]))
...         d[key] = value
...     return out
... 
>>> d = { 'a': 0, 'b': 4 } 
>>> add_to_dict(d, [('a', 2), ])
[('a', 0)]
>>> print(d)
{'a': 2, 'b': 4}

Smells like homework but what they hey..

def add_to_dict(d, kvlist):
    for key, value in kvlist:
        d[key] = value

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

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

Yeah, quite suspicious this is homework... Well, I interpreted the question as requiring to alter the list, removing the tuples, and not updating the dict if the key is already present.

  def add_to_dict(d, kvlist):
      rejected = []
      while len(kvlist) > 0:
           key, value = kvlist.pop()
           if d.has_key(key):
                rejected.append((key, value))
           d[key] = value

      return rejected

Let's break it down:

Write a function add_to_dict(d, key_value_pairs)

def add_to_dict(d, key_value_pairs):
    """
    'd' is a dictionary to be updated
    'key_value_pairs' is a list of tuples where [(key, value)]
    """"

You can iterate over the pairs with, eg, for key, value in key_value_pairs.

def add_to_dict(d, key_value_pairs):
    """
    d is a dictionary to be updated
    key_value_pairs is a list of tuples where [(key, value)]
    """
    for key, value in key_value_pairs:
        pass

You will need to build up a list using append.

def add_to_dict(d, key_value_pairs):
    """
    d is a dictionary to be updated
    key_value_pairs is a list of tuples where [(key, value)]
    """
    for key, value in key_value_pairs:
        pass

my_dict = {}
my_list = []
my_list.append(('key1', 10))
my_list.append(('key2', 20))

add_to_dict(my_dict, my_list)

Now all we have to do is what goes under the for-loop inside the function. Which is:

def add_to_dict(d, key_value_pairs):
    """
    d is a dictionary to be updated
    key_value_pairs is a list of tuples where [(key, value)]
    """
    for key, value in key_value_pairs:
        d[key] = value

my_dict = {}  # we create a empty dict to be updated
my_list = []  # we create a empty list to append

my_list.append(('key1', 10))  # append the first key, value pair
my_list.append(('key2', 20))  # append the second key, value pair

add_to_dict(my_dict, my_list)  #call the function, and pass the dict and list as arguments.

print my_dict  # see the result

Which results in:

{'key2': 20, 'key1': 10}

EDIT:

Now I noticed that the desired output/result of the function are:

[] {'a': 2}
[] {'a': 2, 'b': 4}
[('a', 2)] {'a': 2}

Which is weird since functions should either return something and don't change the global state, or change the global state and don't return anything.

But if that's what the tutorial wants, here what the code would look like:

def add_to_dict(d, key_value_pairs):
    """
    d is a dictionary to be updated
    key_value_pairs is a list of tuples where [(key, value)]
    """
    out = []
    for key, value in key_value_pairs:
        if key in d:
            out.append((key, value))
        d[key] = value
    return out

d = {}
print "->", add_to_dict(d, [('a',2)]),  # -> [], d -> {'a':2}
print "d ->", d
d = {'b':4}
print "->", add_to_dict(d, [('a',2)]),  # -> [], d -> {'a':2,'b':4}
print "d ->", d
d = {'a':0}
print "->", add_to_dict(d, [('a',2)]),  # -> [('a',0)], d -> {'a':2}
print "d ->", d

Which returns:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM