Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get first element of a list inside dictionary and add to Pandas Dataframe column in Python?

I have a dictionary like this:

dict = {"key 1": ["val 1", "val 2"],
        "key 2": ["val 3", "val 4", "val 5"],
        "key 3": ["val 6", "val 7"],
         ...
}

I also have a pandas dataframe that contains all the keys like this:

     key
0    key 1
1    key 2
2    key 3
...

I need to add a new column to the dataframe called first_key that takes the first element of the list inside the dictionary for each key in the dict, so it ends up like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     key      first_key
0    key 1    val 1
1    key 2    val 3
2    key 3    val 6
...

which I have had some trouble with… doing something like this doesn’t work:

df['first_key'] = df['key'].map(dict[WHAT HERE][0])

😀

>Solution :

Try:

dct = {
    "key 1": ["val 1", "val 2"],
    "key 2": ["val 3", "val 4", "val 5"],
    "key 3": ["val 6", "val 7"],
}

df["first_key"] = df["key"].apply(dct.get).str[0]
print(df)

Prints:

     key first_key
0  key 1     val 1
1  key 2     val 3
2  key 3     val 6

Or:

df["first_key"] = df["key"].map(dct).str[0]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading