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

Converting dataframe to dictionary

I have a dataframe which includes two columns, one with state names and the other with state abbreviation, as below:

enter image description here

I’m trying to convert this into a dictionary that looks 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

{AL: Alabama, AK: Alaska, AZ: Arizona, AR: Arkansas, CA: California, CO: Colorado, CT: Connecticut}

I ran the following code:

x = dic.set_index('Abbreviation').T.to_dict('records')

But it converts my dataframe to a list of dictionary, like so:

[{AL: Alabama, AK: Alaska, AZ: Arizona, AR: Arkansas, CA: California, CO: Colorado, CT: Connecticut}]

Is there a way I can convert it to just a dictionary? All the other orientation in the to_dict() function includes the index, which I do not need.

I’m sure this is a very simple problem, but I’ve been having some trouble so any help would be appreciated. Many thanks in advance!

>Solution :

Another solution:

d = dict(zip(df["Abbreviation"], df["State"]))
print(d)

Prints:

{
    "AL": "Alabama",
    "AK": "Alaska",
    "AZ": "Arizona",
    "AR": "Arkansas",
    "CA": "California",
    "CO": "Colorado",
    "CT": "Connecticut",
}
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