简体   繁体   English

创建一个 python 字典,其中值是字符串列表

[英]create a python dictionary where the value is a list of strings

I have a file in which there are 2 names on each line.我有一个文件,其中每行有 2 个名称。 Let's say i have the following input:假设我有以下输入:

name1 name2名称 1 名称 2
name3 name4名称 3 名称 4
name1 name5名称 1 名称 5

I want to make a dictionary like this:我想做一个这样的字典:

name1: [name2, name5]名称1:[名称2,名称5]
name2: name1名称2:名称1
name3: name4名称 3:名称 4
name4: name3名称 4:名称 3
name5: name1名称 5:名称 1

Here is the code I made but i can't figure out what i did wrong..这是我制作的代码,但我无法弄清楚我做错了什么..

d = {} 
for i in range(len(l)): # consider l the input
    d[l[i]] = ""

for i in range(0, len(l), 2):
    e1 = l[i]
    e2 = l[i+1]

    d.update({e1 : [d[e1], e2]}) #i think the update operation is wrong here..
    d.update({e2 : [d[e2], e1]})

You can change the two critical lines to:您可以将两个关键行更改为:

d.setdefault(e1, []).append(e2)
d.setdefault(e2, []).append(e1)

This will start an empty list if the key is not present and then fill it.如果密钥不存在,这将启动一个空列表,然后填充它。

Create a defaultdict d which sets empty lists as the initial values for every key and populate them as you iterate over l .创建一个 defaultdict d ,它将空列表设置为每个键的初始值,并在您遍历l时填充它们。

from collections import defaultdict
l = ['name1', 'name2', 'name3', 'name4', 'name1', 'name5'] # Values come in pairs
d = defaultdict(list) # Defaults all keys to []

for i in range(0, len(l), 2):
    d[l[i]].append(l[i+1])
    d[l[i+1]].append(l[i])

You can use defaultdict:您可以使用默认字典:

>>> from collections import defaultdict

>>> d = defaultdict(list)
>>> for i in range(0, len(l), 2):
...     d[e1].append(e2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM