Pablo Fernandez
Pablo Fernandez

Reputation: 13

Python - Add tuple values to repeated keys in a dict

I've been trying to convert this test.csv file:

a,b,4
a,c,2
b,a,4
b,c,1
b,d,5
c,a,2
c,b,1
c,d,8
c,e,10
d,b,5
d,c,8
d,e,2
d,z,6
e,c,10
e,d,2
e,z,3
z,d,6
z,e,3

Into this formatting. So far when I try to convert it, the repeated keys get override and not added as a second value. Could someone show me how to get this formatting?

G1 = {
    'a': [('b', 4), ('c', 2)],
    'b': [('a', 4), ('c', 1), ('d', 5)],
    'c': [('a', 2), ('b', 1), ('d', 8), ('e', 10)],
    'd': [('b', 5), ('c', 8), ('e', 2), ('z', 6)],
    'e': [('c', 10), ('d', 2), ('z', 3)],
    'z': [('d', 6), ('e', 3)],
}

This is the code that converts the file into a dict, but replaces the new values for the repeated keys. I'd like to know how to add the values as tuples and for repeated keys, add the tuples as second values.

reader = csv.reader(open('test.csv'))
arcos = {}
for row in reader:
    key = row[0]
    arcos[key] = row[1:]

And the result:

{
'a': ['c', 2.0],
 'b': ['d', 5.0],
 'c': ['e', 10.0],
 'd': ['z', 6.0],
 'e': ['z', 3.0],
 'z': ['e', 3.0]
}

I hope what I've requested is possible.

Upvotes: 1

Views: 121

Answers (2)

McGrady
McGrady

Reputation: 11487

You can use groupby method and make this easy:

from itertools import groupby

with open('out.csv') as f:
    print({k:[(i.split(',')[1],i.split(',')[2]) for i in g] for k, g in groupby([i.strip() for i in f],lambda x: x.split(',')[0])})

Result:

 {'a': [('b', '4'), ('c', '2')], 'c': [('a', '2'), ('b', '1'), ('d', '8'), ('e', '10')], 'b': [('a', '4'), ('c', '1'), ('d', '5')], 'e': [('c', '10'), ('d', '2'), ('z', '3')], 'd': [('b', '5'), ('c', '8'), ('e', '2'), ('z', '6')], 'z': [('d', '6'), ('e', '3')]}

Upvotes: 0

Uriel
Uriel

Reputation: 16204

Use defaultdict with the list class, iterate the file and append the tuples:

from collections import defaultdict

G = defaultdict(list)

with open('test.csv') as file:
    for line in file:
        key, letter, digit = line.strip().split(',')
        digit = int(digit)
        G[key].append((letter, digit))

Upvotes: 1

Related Questions