Reputation: 115
I want to change the key names car
into model
and engine
into fuel
. When I run my code only value
gets changed. This is my dictionary:
my_dictionary = {'url': 'www.google.com', 'value': [{'car': 'Mercedes', 'engine': 'Gas'}, {'car': 'Audi', 'engine': 'Diesel'}, {'car': 'Volkswagen', 'engine': 'Hybrid'}]}
This is my code:
new_keys = ['model','fuel']
for key,n_key in zip(my_dictionary.keys(), new_keys):
my_dictionary [n_key] = my_dictionary .pop(key)
Expected outcome:
my_dictionary = {'url': 'www.google.com', 'value': [{'model': 'Mercedes', 'fuel': 'Gas'}, {'model': 'Audi', 'fuel': 'Diesel'}, {'model': 'Volkswagen', 'fuel': 'Hybrid'}]}
PS: The second step is to transport this dictionary to MySQL do you have some tips for this? Do I need to use pandas for example?
Thank you all.
Upvotes: 0
Views: 64
Reputation: 181725
You're modifying the dictionary while iterating over it, which is always a recipe for trouble. One way would be to use list(my_dictionary.keys())
to freeze the keys()
generator into a list, but we can do better.
Also you're relying on the order in which keys appear, which (although guaranteed by recent versions of Python) is not usually well defined.
Taking those both into account:
key_mapping = {'car': 'model', 'engine': 'fuel'}
my_dictionary['value'] = [
{
key_mapping[key]: value
for key, value in car.items()
}
for car in my_dictionary['value']
]
This is using a list comprehension for the containing list, and a dict comprehension inside of that to create each inner dictionary.
Upvotes: 2
Reputation: 91
This should do the trick:
my_dictionary = {'url': 'www.google.com', 'value': [{'car': 'Mercedes', 'engine': 'Gas'}, {'car': 'Audi', 'engine': 'Diesel'}, {'car': 'Volkswagen', 'engine': 'Hybrid'}]}
for i, dictionary in enumerate(my_dictionary['value']):
my_dictionary['value'][i]['model'] = dictionary.pop('car')
my_dictionary['value'][i]['fuel'] = dictionary.pop('engine')
Upvotes: 1
Reputation: 82755
This is one approach using dict
with zip
Ex:
my_dictionary = {'url': 'www.google.com', 'value': [{'car': 'Mercedes', 'engine': 'Gas'}, {'car': 'Audi', 'engine': 'Diesel'}, {'car': 'Volkswagen', 'engine': 'Hybrid'}]}
new_keys = ['model','fuel']
my_dictionary['value'] = [dict(zip(new_keys, i.values())) for i in my_dictionary['value']]
print(my_dictionary)
Output:
{'url': 'www.google.com',
'value': [{'fuel': 'Gas', 'model': 'Mercedes'},
{'fuel': 'Diesel', 'model': 'Audi'},
{'fuel': 'Hybrid', 'model': 'Volkswagen'}]}
Upvotes: 2