How to create a dictionary with columns given as k

2019-09-17 13:16发布

问题:

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.

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!

THERE HAS to be a simple way.

Please help.

回答1:

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()


回答2:

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']}


回答3:

f = open('romEdges.txt')

dic = {}

for l in f:

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