Reputation: 465
If I have 100 columns in a dataframe and I want to create dictionaries of pair of columns, the key would always be a fixed columns. How can it be done?
Let's say we have a dataframe like this:
k v1 v2 ... v99
============================
i 1 2 ... 9
ii 11 22 ... 99
iii 111 222 ... 999
...
I would want dictionaries dict_v1
, dict_v2
... dict_v99
. For example dict_v2
would be:
{'i': 2, 'ii': 22, 'iii': 222, ...}
Upvotes: 3
Views: 118
Reputation: 862611
I suggest create dictionary of dictionaries like:
d = df.set_index('k').to_dict()
print (d)
{'v1': {'i': 1, 'ii': 11, 'iii': 111},
'v2': {'i': 2, 'ii': 22, 'iii': 222},
'v99': {'i': 9, 'ii': 99, 'iii': 999}}
Then each dict is possible select by key:
print (d['v2'])
{'i': 2, 'ii': 22, 'iii': 222}
Another idea should be:
df1 = df.set_index('k')
print (df1)
v1 v2 v99
k
i 1 2 9
ii 11 22 99
iii 111 222 999
print (df1['v2'].to_dict())
{'i': 2, 'ii': 22, 'iii': 222}
What you need is possible, but is bad idea to add names dynamically to a Python namespace.:
for k, v in df.set_index('k').to_dict().items():
globals()[f'dict_{k}'] = v
print (dict_v2)
{'i': 2, 'ii': 22, 'iii': 222}
Upvotes: 2