I need a help to convert the bellow list to a dictionary:
list = [{'Dia': 'qua', 'Promo': 'João', 'Loja': 6697}, {'Dia': 'qui', 'Promo': 'João', 'Loja': 5599}, {'Dia': 'sex', 'Promo': 'João', 'Loja': 7437}]
The output must be:
Output:
dict = {{'Dia': 'qua', 'Promo': 'João', 'Loja': 6697}, {'Dia': 'qui', 'Promo': 'João', 'Loja': 5599}, {'Dia': 'sex', 'Promo': 'João', 'Loja': 7437}}
Right now you have a list that is made up of 3 dictionaries.
But the output that you are asking for is a "dictionary" made up of 3 dictionaries, but python will not allow that.
A dictionary is {"key": value}. So, the best you could do is to string your 3 dictionaries together.
Please correct me if I'm wrong. I often am :)
Nested dictionaries are allowed and useful
eachsub dictionary does require a key, so have made d1, d2 and d3
I added display dict so that you can display contents
newdict = {
'd1': {'Dia': 'qua', 'Promo': 'João', 'Loja': 6697},
'd2': {'Dia': 'qui', 'Promo': 'João', 'Loja': 5599},
'd3': {'Dia': 'sex', 'Promo': 'João', 'Loja': 7437}
}
def display_dict(dictname, level=0):
indent = " " * (4 * level)
for key, value in dictname.items():
if isinstance(value, dict):
print(f'\n{indent}{key}')
level += 1
display_dict(value, level)
else:
print(f'{indent}{key}: {value}')
if level > 0:
level -= 1
if __name__ == '__main__':
display_dict(newdict)
output when run:
Output:
d1
Dia: qua
Promo: João
Loja: 6697
d2
Dia: qui
Promo: João
Loja: 5599
d3
Dia: sex
Promo: João
Loja: 7437
Dictionaries need key/value pairs, so you can either make up a new key, or you can use one of the keys from the dictionaries. Larz60+ created a new key. Below the 'Dia' value is used as a key for each of the sub-dictionaries.
combined_dict = {'qua':{'Promo': 'João', 'Loja': 6697},
'qui':{'Promo': 'João', 'Loja': 5599},
'sex':{'Promo': 'João', 'Loja': 7437}}
You could also use the values for 'Loja' as the key for your sub-dictionaries. You cannot use 'Promo' values as a key for sub-dictionaries because the 'Promo' values are not unique.
Please how can I finish the topic as solved????
just stop posting. All threads remain so that others may benefit from them in the future.
# a list
mylist = [{'Dia': 'qua', 'Promo': 'João', 'Loja': 6697}, {'Dia': 'qui', 'Promo': 'João', 'Loja': 5599}, {'Dia': 'sex', 'Promo': 'João', 'Loja': 7437}]
# dict from list
mydict = {i:mylist[i] for i in range(len(mylist))}