Skip to content
Advertisement

Creating dictionary need more than 1 value to unpack

I have two lists:

managers = ['john', 'karl', 'ricky']
sites = ['site1', 'site2', 'site3']

I also have a json file for each manager:

{
  "results": [
    {
      "id": "employee1",
      "user": {
        "location": "site1"
      }
    },
    {
      "id": "employee2",
      "user": {
        "location": "site1"
      }
    },
    {
      "id": "employee3",
      "user": {
        "location": "site2"
      }
    },
    {
      "id": "employee4",
      "user": {
        "location": "site3"
      }
    }
  ]
}

So now, I want to create a dictionary by to categorize data by site! which is making it challenging for me. The output I need is to show employees for each site.

Here is the code I have:

myDict = dict()

for j in managers:
    for i in range(len(sites)):
        with open(""+j+"-data.json", 'r') as jasonRead:
            json_object = json.loads(jasonRead.read())

            for result in json_object['results']:
                site = (result['user']['location'])

            for employee, manager in map(str.split, str(site), managers[i]):
                myDict.setdefault(managers[i], []).append(site)

The error I get:

  File "test.py", line 25, in <module>
    for employee, manager in map(str.split, str(site), managers[i]):
ValueError: need more than 1 value to unpack

Advertisement

Answer

Instead of looping over sites, just test if the site of the employee is in the list.

The keys of the resulting dictionary should be the site names, not the manager names.

mydict = {}

for manager in managers:
    with open(f'{manager}-data.json') as jasonRead:
        json_object = json.load(jasonRead)
    for result in json_object['results']:
        site = result['user']['location']
        if site in sites:
            mydict.setdefault(site, []).append(result['id'])

print(mydict)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement