将两个列表转换为字典

时间:2016-11-18 08:49:25

标签: python python-3.x

这是我的代码:

def lists_to_dict(coded, plain):
    '''
    (list of str, list of str) -> dict of {str: str}
    Return a dict in which the keys are the items in coded and
    the values are the items in the same positions in plain. The
    two parameters must have the same length.

    >>> d = lists_to_dict(['a', 'b', 'c', 'e', 'd'],  ['f', 'u', 'n', 'd', 'y'])
    >>> d == {'a': 'f', 'b': 'u', 'c': 'n', 'e': 'd', 'd': 'y'}
    True
    '''
    dic = {}
    dic = {key:value for key, value in zip(coded, plain)}
    return dict(dic)

和我的输出:

>>> {'b': 'u', 'c': 'n', 'e': 'd', 'd': 'y', 'a': 'f'}

有人可以告诉我哪里出错了,请帮帮我!

2 个答案:

答案 0 :(得分:1)

要么你可以试试这个......

我在下面提到过两种方式..

Python 3.4.3 (default, Sep 14 2016, 12:36:27) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> d = (['a', 'b', 'c', 'e', 'd'],  ['f', 'u', 'n',   'd', 'y'])
>>> dictionary = dict(zip(d[0], d[1]))
>>> dictionary
{'d': 'y', 'c': 'n', 'b': 'u', 'a': 'f', 'e': 'd'}
>>> dict(zip(*d))
{'d': 'y', 'c': 'n', 'b': 'u', 'a': 'f', 'e': 'd'}

dict(zip(*d)仅在list / tuple的长度为2时使用。如果length大于2,则会出现错误

>>> d = (['a', 'b', 'c', 'e', 'd'],  ['f', 'u', 'n',   'd', 'y'],['1','2','3','4'],['5','6','7','8'])
>>> dict(zip(*d))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 4; 2 is required

答案 1 :(得分:0)

python词典本质上没有排序,如果你需要它们,请使用集合中的OrderedDict按顺序跟随输入列表

from collections import OrderedDict
def lists_to_dict(coded, plain):
    '''
    Return order dictionary follow order of input list
    '''

    # return dict(zip(coded, plain)) # if the order doesn't matter
    return OrderedDict(zip(coded, plain))


# demo
>>> d = lists_to_dict(['a', 'b', 'c', 'e', 'd'], ['f', 'u', 'n', 'd', 'y'])
>>> d
OrderedDict([('a', 'f'), ('b', 'u'), ('c', 'n'), ('e', 'd'), ('d', 'y')])
>>>
>>> for k,v in d.items():
...     print('{} : {}'.format(k,v))
...
a : f
b : u
c : n
e : d
d : y