kevingduck kevingduck -4 years ago 100
Python Question

Building a python dictionary with a dictionary ... from a list

This is probably simple for most python users. I have a list of lists:

adv1 = [9999, 'Group1', 12345, 'team1']
adv2 = [8888, 'Group2', 12341, 'team2']
adv3 = [8888, 'Group2', 46563, 'team3']
adv4 = [8888, 'Group2', 23478, 'team4']

all_adv = [adv1, adv2, adv3, adv4] # <- list of lists


There are 2 'Groups' and 4 'teams' in the data. I am trying to iterate through the all_adv data to create a dictionary sorta like this:

{
Group1 : 9999,
teams: {
team1 : 12345
},
{
Group2 : 8888,
teams: {
team2 : 12341,
team3 : 46563,
team4 : 23478
}
}


which groups all the teams under a 'teams' key in their respective Group. I can't figure out the logic. I want to do something like this:

dict = {}
dict['teams'] = []
for row in all_adv:
dict[row[1]] = row[0]
if row[1] not in dict:
dict['teams'] = []
dict['teams'].append({row[3] : row[2]})

print dict


Output:

{'Group2': 8888, 'Group1': 9999, 'teams': [{'team1': 12345}, {'team2': 12341}, {'team3': 46563}, {'team4': 23478}]}


I'm not sure but am thinking I need to make a list of a dictionary of individual groups that includes a dictionary of teams. Any pointers?

Answer Source

I'd recommend a dictionary of dictionaries (rather than a list of dictionaries), with a key of the group name and a value of another dictionary, containing the group's ID and its teams.

adv1 = [9999, 'Group1', 12345, 'team1']
adv2 = [8888, 'Group2', 12341, 'team2']
adv3 = [8888, 'Group2', 46563, 'team3']
adv4 = [8888, 'Group2', 23478, 'team4']

all_adv = [adv1, adv2, adv3, adv4]

d = {}
for i, n, s, t in all_adv:
    if n not in d:
        d[n] = {'id':i, 'teams':{}}
    d[n]['teams'][t] = s

The result:

>>> import pprint
>>> pprint.pprint(d, width=30)
{'Group1': {'id': 9999,
            'teams': {'team1': 12345}},
 'Group2': {'id': 8888,
            'teams': {'team2': 12341,
                      'team3': 46563,
                      'team4': 23478}}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download