Convert python list to dictionary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Convert python list to dictionary (/thread-31672.html) |
Convert python list to dictionary - akanowhere - Dec-27-2020 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:
RE: Convert python list to dictionary - schascheck - Dec-27-2020 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 :) RE: Convert python list to dictionary - Larz60+ - Dec-27-2020 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:
RE: Convert python list to dictionary - deanhystad - Dec-27-2020 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. RE: Convert python list to dictionary - akanowhere - Dec-27-2020 Please how can I finish the topic as solved???? RE: Convert python list to dictionary - Larz60+ - Dec-27-2020 just stop posting. All threads remain so that others may benefit from them in the future. RE: Convert python list to dictionary - Pedroski55 - Dec-27-2020 # 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))} |