Python Forum
Convert python list to dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert python list to dictionary
#3
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
schascheck likes this post
Reply


Messages In This Thread
Convert python list to dictionary - by akanowhere - Dec-27-2020, 12:45 AM
RE: Convert python list to dictionary - by Larz60+ - Dec-27-2020, 02:54 AM
RE: Convert python list to dictionary - by Larz60+ - Dec-27-2020, 08:15 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 2 612 Apr-29-2024, 04:38 PM
Last Post: Calab
  Dictionary in a list bashage 2 595 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 737 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  How to add list to dictionary? Kull_Khan 3 1,038 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  convert string to float in list jacklee26 6 1,962 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  convert a list to links Pir8Radio 3 1,137 Nov-28-2022, 01:52 PM
Last Post: Pir8Radio
  convert this List Comprehensions to loop jacklee26 8 1,547 Oct-21-2022, 04:25 PM
Last Post: deanhystad
  check if element is in a list in a dictionary value ambrozote 4 2,019 May-11-2022, 06:05 PM
Last Post: deanhystad
  Convert list to interger Clives 5 1,647 May-09-2022, 12:53 PM
Last Post: deanhystad
  Dictionary from a list failed, help needed leoahum 7 2,036 Apr-28-2022, 06:59 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020