Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将两个列表合并为一个dict,该dict可能包含每个键的多个值_Python_Dictionary - Fatal编程技术网

Python 将两个列表合并为一个dict,该dict可能包含每个键的多个值

Python 将两个列表合并为一个dict,该dict可能包含每个键的多个值,python,dictionary,Python,Dictionary,我有两张单子 system = ['System A', 'System B', 'System C'] instrument = ['Instrument 1', 'Instrument 2', 'Instrument 3', 'Instrument 4'] 系统项目可能对应于一个或多个仪器项目,如下所示: dict = {'System A':['Instrument 1', 'Instrument 2'], 'System B':['Instrument 3'], 'System C':

我有两张单子

system = ['System A', 'System B', 'System C']
instrument = ['Instrument 1', 'Instrument 2', 'Instrument 3', 'Instrument 4']
系统项目可能对应于一个或多个仪器项目,如下所示:

dict = {'System A':['Instrument 1', 'Instrument 2'], 'System B':['Instrument 3'], 'System C':['Instrument 4']}
请注意,“系统A”如何有一个列表值,该值建立在仪器列表的前两项之上

为了更好地说明我的问题:

我尝试了dict-comprehension+zip,但显然不起作用。这就是我所尝试的:

system_data_dict = {sys:inst for sys, inst in zip(system, instrument)}
请注意,这不是CSV问题。我获取的数据来自SQL数据库,我需要对其进行解析

我现在正把头撞在键盘上哈哈

提前谢谢


编辑:系统列表已通过set进行解析

为列表提供分组信息

假设您从数据库中获取项目

SELECT System, instrument FROM <src> WHERE System IN ("System A", "System B", "System C")
然后使用字典代码:

# system_data_dict = {sys:inst for sys, inst in items}

# EDIT
system_data_dict = {}
for sys, inst in items:
    if sys in system_data_dict.keys():
        system_data_dict[sys].append(inst)
    else:
        system_data_dict[sys] = [inst]

Python没有MultiDict,因此有两个选项:

使用现有库中的MultiDict,例如,当使用成对列表进行初始化时,将多个值与多次出现的键相关联,而dict只保留最后一个值

系统数据dict=werkzeug.DATASSTRUCTERS.MULTI DICTZIPS系统,仪器 系统数据目录getlist'system A'=>['Instrument 1','Instrument 2'] 或者,通过使用一个常规循环手动完成,即使使用一个我不确定看起来会很糟糕的理解是可行的:使用或方法定义dict映射键到列表并每次附加值

系统数据dict={} 对于拉链系统中的k,v,仪表: 系统\u数据\u dict.setdefaultk,[]附录 系统数据记录[‘系统A’]=>[‘仪器1’、‘仪器2’]
分组是如何工作的?为什么系统A从第二个列表中同时使用仪表1和仪表2,是什么阻止了系统B使用仪表2和仪表3?这里的逻辑是什么?没错。没有指定任务。程序是如何知道的?@Chase这是存储在数据库中的数据,我正在逐行获取。我犯了一个错误,并没有澄清第一个列表是一组获得的数据。我现在就编辑它不起作用,如果一个键在输入中多次出现,那么最终的dict中只会出现最后一个关联的值。项目列表按预期工作,但当我尝试将其转换为dict时,只会存储最后一个键的值。我也试过这样做:system_data_dict={sys:[inst]for sys,inst in items}但它是一样的result@Masklinn很抱歉我没想清楚。进行了编辑,使值现在成为列表。这解决了我的问题!谢谢
# system_data_dict = {sys:inst for sys, inst in items}

# EDIT
system_data_dict = {}
for sys, inst in items:
    if sys in system_data_dict.keys():
        system_data_dict[sys].append(inst)
    else:
        system_data_dict[sys] = [inst]