循环通过字典

时间:2013-11-23 01:12:27

标签: python list dictionary

我试图遍历字典,并从第一个键开始,它看起来像 值和循环遍历列表中的每个元素并将其加倍。完成列表后,它会将键和值添加到新字典中,然后继续到字典中的下一个键并继续该过程。每个键附加的值始终是一个列表。最好不要导入任何模块。

一些输入和输出可以更好地理解代码应该做什么(顺序总是不同的,所以有时候你会有' b'首先或& #39; a'首先。):

>>> create_dict({'a': [1, 2], 'b': [3, 4]})
{'a': ['1', '1', '2', '2'], 'b': ['3', '3', '4', '4']}
>>> create_dict({'a': ['c', 'd'], 'b': ['d', 'e']})
{'a': ['c', 'c', 'd', 'd'], 'b': ['d', 'd', 'e', 'e']}  
>>> create_dict({'a': ['e', 'f'], 'b': ['g', 'h']})
{'a': ['e', 'e', 'f', 'f'], 'b': ['g', 'g', 'h', 'h']}  

到目前为止我写的:

def create_dict(sample_dict):
    '''(dict) -> dict

    Given a dictionary, loop through the value in the first key and double
    each element in the list and add the result to a new dictionary, move on
    to the next key and continue the process.

    >>> create_dict({'a': [1, 2], 'b': [3, 4]})
    {'a': ['1', '1', '2', '2'], 'b': ['3', '3', '4', '4']}
    >>> create_dict({'a': ['c', 'd'], 'b': ['d', 'e']})
    {'a': ['c', 'c', 'd', 'd'], 'b': ['d', 'd', 'e', 'e']}
    >>> create_dict({'name': ['bob', 'smith'], 'last': ['jones', 'li']})
    {'name': ['bob', 'bob', 'smith', 'smith'], 'last': ['jones', 'jones', 'li', 'li']}

    '''
    new_dict = {}
    new_list = []
    for index in sample_dict.values():
        for element in index:
            new_list.extend([element] * 2)
    return new_dict

然而,我得到的结果并不符合我的想法:

>>> create_dict({'name': ['bob', 'smith'], 'last': ['jones', 'li']})
{'last': ['jones', 'jones', 'li', 'li', 'bob', 'bob', 'smith', 'smith'], 'name': ['jones', 'jones', 'li', 'li', 'bob', 'bob', 'smith', 'smith']}
>>> create_dict({'a': [1, 2], 'b': [3, 4]})
{'b': [3, 3, 4, 4, 1, 1, 2, 2], 'a': [3, 3, 4, 4, 1, 1, 2, 2]}

感谢那些帮助的人:)

3 个答案:

答案 0 :(得分:1)

我认为您过早地初始化new_list。它抓住了太多的数据

所以,试试这个:

def create_dict(sample_dict):
new_dict = {}
for key in sample_dict:
    new_list = []
    for val in sample_dict[key]:
        new_list.extend([val] * 2)  
    new_dict[key] = new_list
return new_dict

print create_dict({'a': [1, 2], 'b': [3, 4]})

返回{'a': [1, 1, 2, 2], 'b': [3, 3, 4, 4]}

答案 1 :(得分:1)

dictionary comprehensions

可以简单得多
d = {'a': ['c', 'd'], 'b': ['d', 'e']}
{key:[y for z in zip(value, value) for y in z] for (key, value) in d.items()}
{'a': ['c', 'c', 'd', 'd'], 'b': ['d', 'd', 'e', 'e']}

答案 2 :(得分:0)

def create_dict(sample_dict):
    new_dict = {} #build dict straight
    for key,value in sample_dict.items(): #.items() returns tuples: (key,val)
        new_list = [] #start with a new list for each pair in the dict
        for element in value: #go over each element in 'val'
            new_list.extend([element,element])
        new_dict[key] = new_list
    return new_dict

print create_dict({'name': ['bob', 'smith'], 'last': ['jones', 'li']})

输出:

>>> 
{'last': ['jones', 'jones', 'li', 'li'], 'name': ['bob', 'bob', 'smith', 'smith']}