python 。向字典中的键添加多个项目 - python

我正在尝试根据一组唯一值构建一个字典,以用作键和提供项目的元组压缩列表。

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}

但我得到:

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

到目前为止,这是我的代码:

#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

参考方案

您不需要任何。只需使用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)

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

Python:无法识别Pip命令 - python

这是我拍摄的屏幕截图。当我尝试在命令提示符下使用pip时,出现以下错误消息:pip无法识别为内部或外部命令,可操作程序或批处理文件。我已经检查了这个线程:How do I install pip on Windows?我所能找到的就是我必须将"C:\PythonX\Scripts"添加到我的类路径中,其中X代表python版本。如您在我的…

Python:如何将有效的uuid从String转换为UUID? - python

我收到的数据是 { "name": "Unknown", "parent": "Uncategorized", "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16" }, 我需要将uuid从Strin…

Python 3会流行吗? - python

我已经学习了一些Python 2和Python 3,似乎Python 2总体上比Python 3更好。这就是我的问题所在。是否有充分的理由真正切换到python 3? 参考方案 总体上,甚至在大多数细节上,Python3都比Python2更好。关于第三方库, Python 3落后于的唯一区域是。使Python变得如此出色的原因不仅在于它作为一种语言的内在特性…

Python-如何检查Redis服务器是否可用 - python

我正在开发用于访问Redis Server的Python服务(类)。我想知道如何检查Redis Server是否正在运行。而且如果某种原因我无法连接到它。这是我的代码的一部分import redis rs = redis.Redis("localhost") print rs 它打印以下内容<redis.client.Redis o…