如何使用给定的列作为键和值来创建字典 [英] 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
第一列是点的列表,第二列是点的邻居的列表.我想把它做成字典,以便 {A:'S','T','Z',B:'F','G','P'等},等等.
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.
鉴于文本文件是两列,我尝试这样做的是
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)
我尝试制作2个列表,1个键和1个值,并尝试将它们与字典进行比较,等等,但我做对了!
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!
有一种简单的方法.
请帮助.
推荐答案
对于只想从列中创建简单字典而又不重复键值的人们来说,这应该可行:
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:
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()
这篇关于如何使用给定的列作为键和值来创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!