M_S_N
M_S_N

Reputation: 2810

How to create a pandas Series from dict with non unique keys?

I am trying to create a pandas Series from dict that contains non-unique keys. But pandas keep discarding similar keys and loads only the last one.

    my_dict1= {'Country':'US','Country':'UK','Country':'Japan','Country':'China',}
    pd.Series(my_dict1)

Output:

Country    China
dtype: object

Any turn arround possible that it inclues all the keys and values

Upvotes: 1

Views: 178

Answers (2)

kmcodes
kmcodes

Reputation: 857

Dict needs unique keys. You need to do something as below, second option can be created by dict + zipping the list of countries with a range.

Option 1

my_dict1= {'Country1':'US','Country2':'UK','Country3':'Japan','Country4':'China',}

Option 2

country_list = ["US","UK"]
indexes = range(2)
country_dict = dict(zip(indexes,country_list))

Output

country_dict={'0':'US', '1':'UK',}

Upvotes: 2

Mpark
Mpark

Reputation: 11

You could probably change it to:


pd.Series([v for k, v in mydict.items()])

Upvotes: 0

Related Questions