2个列表到字典ISU

2024-06-06 23:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张单子:

list1 = ['r', '8', 'w', 'm', 'f', 'c', 'd',...]
list2 = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF',...]

我想把这两本书都编入词典,以便:

{'r':'AA', '8':'AB', 'w':'AC', 'm':'AD',...}

我试过使用:

dictionary = dict(zip(list1, list2))

但是,我相信这个函数会进行某种奇怪的排序,因为如果我打印“dictionary”,会得到以下输出:

{'1': 'BE', '0': 'EB', '3': 'CE', '2': 'FE', '5': 'DB',...}

为什么会这样,如何产生预期的产出?你知道吗


Tags: 函数dictionaryabzipdictadac词典
3条回答

字典是一种无序的数据结构。两个列表中的项目仍将正确配对,但顺序将丢失。你知道吗

如果需要在dict中保留列表的顺序,可以使用^{}。请注意,OrderedDict的性能不如常规的dict,所以除非您确实需要排序,否则不要使用它们。你知道吗

>>> from collections import OrderedDict
>>> list1 = ['r', '8', 'w', 'm', 'f', 'c', 'd']
>>> list2 = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF']
>>> OrderedDict(zip(list1, list2))
OrderedDict([('r', 'AA'),
             ('8', 'AB'),
             ('w', 'AC'),
             ('m', 'AD'),
             ('f', 'AE'),
             ('c', 'AF')])

字典的行为就像无序的列表,因此它不得不尝试按照[在python文档中解释的](https://docs.python.org/2/tutorial/datastructures.html#dictionaries)对它们进行排序。但是,使用循环指定值)

但是,可以使用循环将它们附加到空字典中,如下所示:

myDict = {}
list1 = ['r', '8', 'w', 'm', 'f', 'c', 'd',...]
list2 = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF',...]

#To prevent different length issues,
#  set max and min length of both lists
max_len = max(len(list1), len(list2))
min_len = min(len(list1), len(list2))
list1IsBigger = len(list1) > len(list2)


# We loop using the min length
for n in xrange(0, min_len):
    myDict[list1[n]] = list2[n]

#From here, do whatever you like with
# remaining items from longer list

if len(list1) != len(list2):
    for n in xrange(min_len, max_len):
        if list1IsBigger:
            #Do whatever with list1 here
        else:
            #Do whatever with list2 here

Python dictionary, how to keep keys/values in same order as declared?

这本词典不是要订的。为此,请使用orderedDict

相关问题 更多 >