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

Create a parent child tree dictionary based on two columns in dataframe

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?

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

Kind regards

>Solution :

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': ''}
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