Reputation: 41
I have a dataframe which includes two columns, one with state names and the other with state abbreviation, as below:
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!
Upvotes: 1
Views: 40
Reputation: 195408
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",
}
Upvotes: 2
Reputation: 260335
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'}
Upvotes: 1