简体   繁体   中英

Python: Store the data into two lists and then convert to a dictionary

I am new to python, and have a question regarding store columns in lists and converting them to dictionary as follow:

I have a data in two column shown below, with nodes(N) and edges(E), and I want to first make a list of these two columns and then make a dictionary of those two lists as

{1:[9,2,10],2:[10,111,9],3:[166,175,7],4:[118,155,185]} .

How can I do that? Thanks.

N   E           
1   9       
1   2       
1   10      
2   10      
2   111     
2   9       
3   166     
3   175     
3   7       
4   118     
4   155     
4   185

A defaultdict is a subclass of dict which would be useful here:

import collections
result=collections.defaultdict(list)
for n,e in zip(N,E):
    result[n].append(e)
yourDict={}
for line in file('r.txt', 'r'):
    k , v =  line.split()
    if k in yourDict.keys():
         yourDict[k].append(v)
    else:
         yourDict[k] = [v]

print  yourDict

Output: (You can always remove N:E in the last)

{'1': ['9', '2', '10'], '3': ['166', '175', '7'], '2': ['10', '111', '9'], '4': ['118', '155', '185'], 'N': ['E']}

The following does not have a for loop over the edges. That iteration is handled internally by Python using built-in methods, and it may be faster for large graphs:

import itertools
import operator

N = [ 1, 1, 1, 2, 2]
E = [ 2, 3, 5, 4, 5]

iter_g = itertools.groupby(zip(N,E), operator.itemgetter(0))

dict_g = dict( (v, map(operator.itemgetter(1), n)) for v,n in iter_g )

Also, if you only need the data once, you could just use iter_g and not construct the dictionary.

a bit slower than unutbu's version, but shorter :)

result = { }
for n, e in ( line.split( ) for line in open( 'r.txt' ) ):
    result[ n ] = result.setdefault( n, [ ] ) + [ e ]

This does exactly what you wanted:

import collections

N = []
E = []
with open('edgelist.txt', 'r') as inputfile:
    inputfile.readline()  # skip header line
    for line in inputfile:
        n,e =  map(int,line.split())
        N.append(n)
        E.append(e)

dct = collections.defaultdict(list)
for n,e in zip(N,E):
    dct[n].append(e)
dct = dict(dct)
print dct
# {1: [9, 2, 10], 2: [10, 111, 9], 3: [166, 175, 7], 4: [118, 155, 185]}

Here is the short answer:

l1 = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
l2 = [9, 2, 10, 10, 111, 9, 166, 175, 7, 118, 155,185]

d = dict((i,[j for j,k in zip(l2,l1) if k == i]) for i in frozenset(l1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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