Python。向di中的键添加多个项

2024-09-26 22:11:34 发布

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

我试图从一组惟一值构建dict作为键,并用压缩的元组列表来提供项。在

set = ("a","b","c")

lst 1 =("a","a","b","b","c","d","d")
lst 2 =(1,2,3,3,4,5,6,)

zip = [("a",1),("a",2),("b",3),("b",3),("c",4),("d",5)("d",6)

dct = {"a":1,2 "b":3,3 "c":4 "d":5,6}

但我得到了:

^{pr2}$

以下是我目前为止的代码:

#make two lists 

rtList = ["EVT","EVT","EVT","EVT","EVT","EVT","EVT","HIL"]
raList = ["C64G","C64R","C64O","C32G","C96G","C96R","C96O","RA96O"]

# make a set of unique codes in the first list

routes = set()
for r in rtList:
    routes.add(r)

#zip the lists

RtRaList = zip(rtList,raList)
#print RtRaList

# make a dictionary with list one as the keys and list two as the values

SrvCodeDct = {}

for key, item in RtRaList:
    for r in routes:
        if r == key:
            SrvCodeDct[r] = item

for key, item in SrvCodeDct.items():
    print key, item

Tags: thekeyinformakezipitemlist
3条回答

dicts中,所有键都是唯一的,每个键只能有一个值。在

解决这个问题最简单的方法是将字典的值设为list,以模拟所谓的多重映射。在列表中,有键映射到的所有元素。在

编辑:

您可能想查看这个PyPI包:https://pypi.python.org/pypi/multidict

不过,在引擎盖下,它可能会像上面描述的那样工作。在

阿飞,没有什么内置的支持你所追求的。在

您可以使用^{}方法来实现这一点:

my_dict = {}
for i, j in zip(l1, l2):
    my_dict.setdefault(i, []).append(j)

它将返回my_dict的值:

^{pr2}$

或者,使用TigerhawkT3提到的^{}。在


代码问题:您没有检查现有的key。每次执行SrvCodeDct[r] = item操作时,都会用item值更新r键的上一个值。为了解决这个问题,您必须将if条件添加为:

l1 = ("a","a","b","b","c","d","d")
l2 = (1,2,3,3,4,5,6,)

my_dict = {}
for i, j in zip(l1, l2):
    if i in my_dict:          # your `if` check 
        my_dict[i].append(j)  # append value to existing list
    else:
        my_dict[i] = [j]  


>>> my_dict
{'a': [1, 2], 'c': [4], 'b': [3, 3], 'd': [5, 6]}

然而,可以使用^{}(如TigerhawkT3所述)或使用^{}方法来简化此代码:

my_dict = {}
for i, j in zip(l1, l2):
    my_dict.setdefault(i, []).append(j)

你不需要这些。只需使用collections.defaultdict。在

import collections

rtList = ["EVT","EVT","EVT","EVT","EVT","EVT","EVT","HIL"]
raList = ["C64G","C64R","C64O","C32G","C96G","C96R","C96O","RA96O"]

d = collections.defaultdict(list)

for k,v in zip(rtList, raList):
    d[k].append(v)

相关问题 更多 >

    热门问题