简体   繁体   English

如何用给定的列作为键和值创建字典

[英]How to create a dictionary with columns given as keys and values

Ok so I am given two columns 好吧,我得到两列

A S

A T

A Z

B F

B G

B P

B U

C D

C P

C R

D M

E H

F S

H U

The 1st column is a list of points, and the second column is the list of the neighbors of the points. 第一列是点的列表,第二列是点的邻居的列表。 I would like to make it a dictionary so that {A:'S','T','Z', B:'F','G','P' etc} and so on. 我想将其设为字典,以便{A:'S','T','Z',B:'F','G','P'等}等。

What I have tried doing is this, given that the text file is the two columns. 鉴于文本文件是两列,因此我尝试这样做。

edges = open('romEdges.txt')

edgeslist = edges.read().split()

edgeskeys = edgeslist[::2]

edgesvalues = edgeslist[1::2]


dictionary = {}

for items in edgeskeys:

    dictionary[items]=[]

dictionary = OrderedDict(sorted(dictionary.items(), key=lambda t: t[0]))

for items in edgeskeys:

    if edgeskeys[items]==dictionary[items]:

        print()

print(dictionary)

I have tried making 2 lists, 1 of keys and 1 of values, and tried comparing them to the dictionary, etc, and I just can't get it right! 我尝试制作2个列表,1个键和1个值,并尝试将它们与字典进行比较,等等,但我做对了!

THERE HAS to be a simple way. 有一种简单的方法。

Please help. 请帮忙。

Why not just plain simple line-by-line processing? 为什么不仅仅进行简单的逐行处理呢?

f = open('romEdges.txt')
dic = {}
for l in f:
    k, v = l.split()
    if k in dic:
        dic[k].extend(v)
    else:
        dic[k] = [v]
f.close()
print dic

Output from your input: 输入的输出:

{'A': ['S', 'T', 'Z'], 'C': ['D', 'P', 'R'], 'B': ['F', 'G', 'P', 'U'], 'E': ['H'], 'D': ['M'], 'F': ['S'], 'H': ['U']}

For People who just want to create a simple dictionary from colums without recurring keyvalues this should work: 对于只想从列创建简单字典而又不重复键值的用户,这应该可行:

 edges = open('romEdges.txt')
 dict = {line[:1]:line[1:] for line in edges}
 print dict
 edges.close()

now you have possibly some whitespaces or Backspaces in the values, then you can replace() that with empty strings: 现在您的值中可能包含一些空格或Backspace,那么您可以使用空字符串replace():

 edges = open('romEdges.txt')
 dict = {line[:1]:line[1:].split()[0] for line in edges}
 print dict
 edges.close()

if you have multiple colums, and you want to have a list out of the following colums to that keyvalue: 如果您有多个列,并且想要从以下列中找到该键值的列表:

 edges = open('romEdges.txt')
 dict = {line[:1]:line[1:].split() for line in edges}
 print dict
 edges.close()
f = open('romEdges.txt')

dic = {}

for l in f : 对于f中的 l

k, v = l.split('\t')
dic.setdefault(k,[])
if k in dic.keys():
    dic[k].extend([v.strip()])
else:
    dic[k] =[v]
f.close()

print dic

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

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