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"
]
}
>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 _]).