Search code examples
pythonpandasdictionarydict-comprehension

Python dictionary comprehension with Pandas


I am trying to create a dictionary from two columns of a DataFrame (df)

mydict={x :y for x in df['Names'] for y in df['Births']}

But all of the values are the same(the last value in the column)!

{'Bob': 973, 'Jessica': 973, 'John': 973, 'Mary': 973, 'Mel': 973}

I checked the column and it has many other values, what am I doing wrong?


Solution

  • I think Abdou hit the nail on the head with dict(zip(dff['Names'], dff['Births'])), but if you want to do it with a dict comprehension you can do this:

        In [1]: import pandas as pd
    
        In [2]: df = pd.DataFrame(
           ...: [{'Births': 971, 'Names': 'Bob'},
           ...:  {'Births': 972, 'Names': 'Jessica'},
           ...:  {'Births': 973, 'Names': 'John'},
           ...:  {'Births': 974, 'Names': 'Mary'},
           ...:  {'Births': 975, 'Names': 'Mel'}])
    
        In [3]: {d['Names']: d['Births'] for d in df.to_dict(orient='records')}
        Out[3]: {'Bob': 971, 'Jessica': 972, 'John': 973, 'Mary': 974, 'Mel': 975}