O
O
oe24y2021-09-18 16:49:00
Python
oe24y, 2021-09-18 16:49:00

How to make a multidimensional dictionary with grouping in Python (see example)?

Let me explain with an example. There is json:

{'city':'Moscow', 'manager':'Igor'},
{'city':'Kazan', 'manager':'Valera'},
{'city':'Moscow', 'manager':'Olga'},
{'city':'Kazan', 'manager':'Natalia'},
{'city':'Moscow', 'manager':'Oleg'},

How to easily and competently make such a structure?

'Moscow': ['Igor','Olga','Oleg'],
'Kazan': ['Valera','Natalia']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2021-09-18
@oe24y

res = {}
for d in ({'city': 'Moscow', 'manager': 'Igor'},
          {'city': 'Kazan', 'manager': 'Valera'},
          {'city': 'Moscow', 'manager': 'Olga'},
          {'city': 'Kazan', 'manager': 'Natalia'},
          {'city': 'Moscow', 'manager': 'Oleg'}):
    res.setdefault(d['city'], []).append(d['manager'])
print(res)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question