Python Forum
Lists in Dictionaries Assistance
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Lists in Dictionaries Assistance
#2
here is more general example that will create a dict with devices for each department
note that in your data 'department' is a list, even with one value. I don't know if it is possible to have more than one department in this list

import yaml
from collections import defaultdict
     
with open('router.cfg', 'r') as lb:
    try:
        test = (yaml.load(lb))
    except yaml.YAMLError as exc:
        print(exc)
    
maindict = test['device_list']
devices = defaultdict(list)
for location in maindict.values():
    for department in location['department']:
        devices[department].extend(location['devices']) 

print(devices)
print(devices['FIN'])
this could be shortened with list comprehension but now is more explicit
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
Lists in Dictionaries Assistance - by wfsteadman - May-05-2018, 03:06 PM
RE: Lists in Dictionaries Assistance - by buran - May-05-2018, 04:44 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,376 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Comparing items from 2 lists of dictionaries illwill 7 2,766 Sep-14-2020, 10:46 PM
Last Post: bowlofred
  Searching through Nested Dictionaries and Lists Dave_London 1 7,621 Jul-09-2020, 03:36 PM
Last Post: mrdominikku
  Finding value in nested dictionaries with lists mart79 16 8,064 Mar-08-2020, 08:16 PM
Last Post: ndc85430
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,277 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Nested Dictionaries with Lists BriHaug 1 52,905 Feb-23-2019, 02:10 AM
Last Post: ichabod801
  Help with Dictionaries and List of Lists artblinked 7 3,115 Feb-14-2019, 05:07 PM
Last Post: artblinked
  Help in understanding scope of dictionaries and lists passed to recursive functions barles 2 3,211 Aug-11-2018, 06:45 PM
Last Post: barles

Forum Jump:

User Panel Messages

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