2015-09-03 60 views
0

我正在写一个函数add_to_dict(d, key_value_pairs),它将给定的每个键/值对添加到给定字典。参数key_value_pairs将是表单(键,值)中的元组列表。如何更新字典并返回更新键/值对

函数应返回已更改的所有键/值对(使用其原始值)的列表。

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

我在这里得到的东西似乎完全不对,我现在还没有线索。

+0

你是否知道字典有一个'update'方法,它基本上已经做了你正在做的事情?除了返回键/值对的列表外,这是字典的'items'方法的用途。 – mkrieger1

回答

0

从我的理解,你想添加一个键/值元组列表的字典。该函数将返回所有已更改的键/值对。我评论了我在代码中发现的问题。

def add_to_dict(d,key_value_pairs): 
    key_value_pairs=() #This changes your list of key/value tuples into an empty tuple, which you probably don't want 
    thelist=[] 
    thelist.append(list(d)) #This appends all of the keys in d to thelist, but not the values 
    for key, value in key_value_pairs: 
     d[value]=key #You switched the keys and values 
    thelist.append(list(key_value_pairs)) #This is already a list, so list() is unnecessary 
    return thelist 

我会建议简单地返回key_value_pairs,因为它已经包含了所有被修改的键和值。如果您需要更多关于如何解决问题的详细信息,请告知我,但请先尝试自行解决问题。