Eoin Dowling
Eoin Dowling

Reputation: 433

Pandas column of list of keys and column of list of values to a column of a list of dictionaries

I have a pandas dataframe, one column contains data values of type list of strings. Another column contains data values of type list of integer. This might look like

           keys             values
0  ['key1','key2','key3']  [0,1,2]
1  ['key1','key2','key3']  [4,5,6]
2  ['key2','key1','key3']  [7,3,6] 

What I would like to do is have a column of dictionary type values in which e.g.,

           keys             values               dicts
0  ['key1','key2','key3']  [0,1,2]   {'key1':0,'key2':1,'key3':3}
1  ['key1','key2','key3']  [4,5,6]   {'key1':4,'key2':5,'key3':6}
2  ['key2','key1','key3']  [7,3,6]   {'key2':7,'key1':3,'key3':6} 

Assume that both lists across the two column are ordered such that df['keys'][0][0] would correspond to df['values'][0][0] etc.

What I would ideally like to do a brief dict comprehension to achieve this. My thought process has led me to attempt something along the lines of:

df['dicts'] = {k:v for (k,v) in [x for x in zip(df['keys'], df['values'])]}

Which did not succeed, producing a type error:

<Ipython-input-416-0c2823a27ccf> in <module>
----> 1 df['dicts']= dict(zip(df['keys'], df['values']))

TypeError: unhashable type: 'list'

As well as:

df['dicts']= dict(zip(df['keys'], df['values']))

Which fails, producing the following type error:

<Ipython-input-416-0c2823a27ccf> in <module>
----> 1 df['dicts']= dict(zip(df['keys'], df['values']))

TypeError: unhashable type: 'list'

Upvotes: 2

Views: 1538

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

Try:

df['dicts'] = [dict(zip(x,y)) for x,y in zip(df['keys'], df['values'])]

Or with unpack:

df['dicts'] = [dict(zip(*u)) for u in zip(df['keys'], df['values'])]

Upvotes: 2

Related Questions