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

Split dictionary values into two separate values

I have the following dictionary which I want to split the lists into two distinct lists with different keys.

{
   "industry": [
      [
         "IT Services and IT Consulting",
         "New York City, NY"
      ],
      [
         "IT Services and IT Consulting",
         "La Jolla, California"
      ],
      [
         "Software Development",
         "Atlanta, GA"
      ]
   ]
}

I am expecting to have as output:

{
   "industry": [
      "IT Services and IT Consulting",
      "IT Services and IT Consulting",
      "Software Development"
   ],
   "country": [
      "New York City, NY",
      "La Jolla, California",
      "Atlanta, GA"
   ]
}

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

>Solution :

d = {
    "industry": [
      [
         "IT Services and IT Consulting",
         "New York City, NY"
      ],
      [
         "IT Services and IT Consulting",
         "La Jolla, California"
      ],
      [
         "Software Development",
         "Atlanta, GA"
      ]
    ]
}

res = {
    'industry': [t[0] for t in d['industry']],
    'country': [t[1] for t in d['industry']]
}
print(res)

prints

{'industry': ['IT Services and IT Consulting',
  'IT Services and IT Consulting',
  'Software Development'],
 'country': ['New York City, NY', 'La Jolla, California', 'Atlanta, GA']}

Alternative solution:

industry, country = list(zip(*d['industry']))
res = {'industry': industry, 'country': country}

Explanation: Given your dictionary d, create a new dictionary res by iterating over each tuple t = (industry, country) in the list d["industry"] and using the first element t[0] = industry for the "industry" list in res and the second element t[1] = country for the "country" list in res via a list comprehension ([_ for _ in _]).

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