sergey_208
sergey_208

Reputation: 654

How to convert a list into a dictionary which uses tuple as a key

I'd like to read an excel table with Panda, and create a list of tuples. Then, I want to convert the list into a dictionary which has a tuple as key. How can I do that?

Here is the table that I am reading;

A B 0.6

A C 0.7

C D 1.0

C A 1.2

D B 0.7

D C 0.6

Here is how I read my table;

import pandas as pd

df= pd.read_csv("my_file_name.csv", header= None)  

my_tuple = [tuple(x) for x in df.values]

Now, I want to have the following structure.

my_data =  {("A", "B"): 0.6,

            ("A", "C"): 0.7,

            ("C", "D"): 1,

            ("C", "A"): 1.2,

            ("D", "B"): 0.7,

            ("D", "C"): 0.6}

Upvotes: 2

Views: 365

Answers (5)

Vaishali
Vaishali

Reputation: 38415

Set_index and to_dict

df.set_index(['a', 'b']).c.to_dict()

{('A', 'B'): 0.6,
 ('A', 'C'): 0.7,
 ('C', 'A'): 1.2,
 ('C', 'D'): 1.0,
 ('D', 'B'): 0.7,
 ('D', 'C'): 0.6}

Option2: Another solution using zip

dict(zip(df[['A', 'B']].apply(tuple, 1), df['C']))

Option 3:

k = df[['A', 'B']].to_records(index=False).tolist()
dict(zip(k, df['C']))

Upvotes: 3

ALollz
ALollz

Reputation: 59549

A comprehension will work well for smaller frames:

dict((tuple((a, b)), c) for a,b,c in df.values)
#{('A', 'B'): 0.6,
# ('A', 'C'): 0.7,
# ('C', 'A'): 1.2,
# ('C', 'D'): 1.0,
# ('D', 'B'): 0.7,
# ('D', 'C'): 0.6}

If having issues with ordering:

from collections import OrderedDict

d = OrderedDict((tuple((a, b)), c) for a,b,c in df.values)
#OrderedDict([(('A', 'B'), 0.6),
#             (('A', 'C'), 0.7),
#             (('C', 'D'), 1.0),
#             (('C', 'A'), 1.2),
#             (('D', 'B'), 0.7),
#             (('D', 'C'), 0.6)])

Upvotes: 1

Shervin Hariri
Shervin Hariri

Reputation: 105

If you would use simple code:

this one would not use any importing something like panda :

def change_csv(filename):
    file_pointer = open(filename, 'r')
    data = file_pointer.readlines()
    dict = {}
    file_pointer.close()
    for each_line in data:
        a, b, c =  each_line.strip().split(" ")
        dict[a, b] = c
    return dict

so out put of this yours.

and out put is :

{('A', 'B'): '0.6', ('A', 'C'): '0.7', ('C', 'D'): '1.0', ('C', 'A'): '1.2', ('D', 'B'): '0.7', ('D', 'C'): '0.6'}

Upvotes: 1

m13op22
m13op22

Reputation: 2337

This is less concise than @Vaishali's answer but gives you more of an idea of the steps.

vals1 = df['A'].values
vals2 = df['B'].values
vals3 = df['C'].values

dd = {}
for i in range(len(vals1)):
    key = (vals1[i], vals2[i])
    value = vals3[i]
    dd[key] = value

{('A', 'B'): '0.6',
('A', 'C'): '0.7',
('C', 'D'): '1.0',
('C', 'A'): '1.2',
('D', 'B'): '0.7',
('D', 'C'): '0.6'}

Upvotes: 1

jrjames83
jrjames83

Reputation: 901

Jan - here's one idea: just create a key column using the pandas apply function to generate a tuple of your first 2 columns, then zip them up to a dict.

import pandas as pd
df = pd.read_clipboard()
df.columns = ['first', 'second', 'value']
df.head()

def create_key(row):
    return (row['first'], row['second'])

df['key'] = df.apply(create_key, axis=1)

dict(zip(df['key'], df['value']))

{('A', 'C'): 0.7,
 ('C', 'A'): 1.2,
 ('C', 'D'): 1.0,
 ('D', 'B'): 0.7,
 ('D', 'C'): 0.6}

Upvotes: 1

Related Questions