Home > Back-end >  Create a parent child tree dictionary based on two columns in dataframe
Create a parent child tree dictionary based on two columns in dataframe

Time:08-10

Suggest I've a dataframe containing countries and cities looking like this:

data = {'Parent':['Netherlands','Belgium','Germany','France'],'Child':['Amsterdam','Brussels','Berlin', '']}

I want to create a tree dictionary depicting which city belongs to which country. In this example I the country France has no cities, I don't want to have the empty values as child node in the dictionary.

Can someone point me into the right direction on what to use to reach this solution?

Kind regards

CodePudding user response:

Using pandas:

df = pd.DataFrame(data)
df.transpose()

                  0         1        2       3
Parent  Netherlands   Belgium  Germany  France
Child     Amsterdam  Brussels   Berlin

Or using zip:

dict(zip(*data.values()))

{'Netherlands': 'Amsterdam', 'Belgium': 'Brussels', 'Germany': 'Berlin', 'France': ''}
  • Related