Home > Back-end >  Converting dataframe to dictionary
Converting dataframe to dictionary

Time:08-10

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:

{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!

CodePudding user response:

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",
}

CodePudding user response:

Use a Series:

x = dic.set_index('Abbreviation')['State'].to_dict()

output:

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