I have two lists:
JavaScript
x
3
1
managers = ['john', 'karl', 'ricky']
2
sites = ['site1', 'site2', 'site3']
3
I also have a json file for each manager:
JavaScript
1
29
29
1
{
2
"results": [
3
{
4
"id": "employee1",
5
"user": {
6
"location": "site1"
7
}
8
},
9
{
10
"id": "employee2",
11
"user": {
12
"location": "site1"
13
}
14
},
15
{
16
"id": "employee3",
17
"user": {
18
"location": "site2"
19
}
20
},
21
{
22
"id": "employee4",
23
"user": {
24
"location": "site3"
25
}
26
}
27
]
28
}
29
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:
JavaScript
1
13
13
1
myDict = dict()
2
3
for j in managers:
4
for i in range(len(sites)):
5
with open(""+j+"-data.json", 'r') as jasonRead:
6
json_object = json.loads(jasonRead.read())
7
8
for result in json_object['results']:
9
site = (result['user']['location'])
10
11
for employee, manager in map(str.split, str(site), managers[i]):
12
myDict.setdefault(managers[i], []).append(site)
13
The error I get:
JavaScript
1
4
1
File "test.py", line 25, in <module>
2
for employee, manager in map(str.split, str(site), managers[i]):
3
ValueError: need more than 1 value to unpack
4
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.
JavaScript
1
12
12
1
mydict = {}
2
3
for manager in managers:
4
with open(f'{manager}-data.json') as jasonRead:
5
json_object = json.load(jasonRead)
6
for result in json_object['results']:
7
site = result['user']['location']
8
if site in sites:
9
mydict.setdefault(site, []).append(result['id'])
10
11
print(mydict)
12