I've been trying to convert a list of dictionaries into a single dictionary in such a way where each key is <city>, <state>
and each value is <county>
.
In short I have a list that looks like this.
[{'city': 'Normal',
'county': 'Madison County',
'state': 'Alabama'},
{'city': 'Birmingham',
'county': 'Jefferson County',
'state': 'Alabama'},
{'city': 'Montgomery',
'county': 'Montgomery County',
'state': 'Alabama'}]
And I would like to change it into something like this
{'Normal, Alabama': 'Madison County',
'Birmingham, Alabama': 'Jefferson County',
'Montgomery, Alabama': 'Montgomery County'}
I tried dictionary comprehensions but can't seem to add two different keys at once.
So I know the code below will give me a dictionary with cities and counties for key value pairs
new_dict = {x['city']: x['county'] for x in counties}
However, how do I add two different keys since something like new_dict = {x['city','state']: x['county'] for x in counties}
won't work
CodePudding user response:
You can use dict comprehension:
lst = [{'city': 'Normal',
'county': 'Madison County',
'state': 'Alabama'},
{'city': 'Birmingham',
'county': 'Jefferson County',
'state': 'Alabama'},
{'city': 'Montgomery',
'county': 'Montgomery County',
'state': 'Alabama'}]
output = {f"{dct['city']}, {dct['state']}": dct['county'] for dct in lst}
print(output)
# {'Normal, Alabama': 'Madison County', 'Birmingham, Alabama': 'Jefferson County', 'Montgomery, Alabama': 'Montgomery County'}
Here, you combine two keys by using f-string.
CodePudding user response:
You can use string concatenation to form the key:
data = [{'city': 'Normal',
'county': 'Madison County',
'state': 'Alabama'},
{'city': 'Birmingham',
'county': 'Jefferson County',
'state': 'Alabama'},
{'city': 'Montgomery',
'county': 'Montgomery County',
'state': 'Alabama'}]
new_dict = {x['city'] ", " x['state']: x['county'] for x in data}
print(new_dict)
This outputs:
{'Normal, Alabama': 'Madison County', 'Birmingham, Alabama': 'Jefferson County', 'Montgomery, Alabama': 'Montgomery County'}
CodePudding user response:
Why not just a simple for loop?
l = [
{"city": "Normal", "county": "Madison County", "state": "Alabama"},
{"city": "Birmingham", "county": "Jefferson County", "state": "Alabama"},
{"city": "Montgomery", "county": "Montgomery County", "state": "Alabama"},
]
result = dict()
for x in l:
city = x.get("city")
state = x.get("state")
key = f"{city}, {state}"
value = x.get("county")
result[key] = value
print(result)