user13723838
user13723838

Reputation: 1

Looping over python dictionary of dictionaries

I have a python dictionary like below

    car_dict=
{
'benz': {'usa':876456, 'uk':965471},
'audi' : {'usa':523487, 'uk':456879},
'bmw': {'usa':754235, 'uk':543298}
}

I need the output like below

benz,876456,965471
audi,523487,456879
bmw,754235,543298

and also in sorted form as well like below

audi,523487,456879
benz,876456,965471
bmw,754235,543298

Please help me in getting both outputs

Upvotes: 0

Views: 60

Answers (5)

Glenn Mackintosh
Glenn Mackintosh

Reputation: 2779

I like the list comprehension answer given by @DarrylG however you do not really need the lambda expression in this case.

sorted() will just do the sort by key by default, so you can just use :

data = [[car] + list(regions.values()) for car, regions in sorted(car_dict.items())]

I would also make another slight change. If you wanted more explicit control over the region ordering (or wanted a different ordering, you could replace the [car] + list(regions.values()) with [car, regions['usa'], regions['uk']] like this:

data = [[car, regions['usa'], regions['uk']] for car, regions in sorted(car_dict.items())]

Of course, that means that if you added more regions you would have to change this, but I prefer setting the order explicitly.

Upvotes: 0

Earnest
Earnest

Reputation: 151

Find below the solution,

car_dict = {
            'benz': {'usa':876456, 'uk':965471},
            'audi' : {'usa':523487, 'uk':456879},
            'bmw': {'usa':754235, 'uk':543298}
           }

keys = list(car_dict.keys())
keys.sort()

for i in keys:
    print ( i, car_dict[i] ['usa'], car_dict[i] ['uk'])

Upvotes: 0

DarrylG
DarrylG

Reputation: 17166

To print the data

# Use List comprehension to sorted list of values from car, USA, UK fields
data = [[car] + list(regions.values()) for car, regions in sorted(car_dict.items(), key=lambda x:x[0])]
for row in data:
  print(*row, sep = ',')

Output

audi,523487,456879
benz,876456,965471
bmw,754235,543298

Explanation

Sort items by car

for car, regions in sorted(car_dict.items(), key=lambda x:x[0])

Each inner list in list comprehension to be row of car, USA, UK values

[car] + list(regions.values())

Print each row comma delimited

for row in data:
    print(*row, sep = ',')

Upvotes: 1

Mathew Paul
Mathew Paul

Reputation: 181

Are you looking to print the outputs or just organize the data in a better format for analysis.

If latter, I would use pandas and do the following

import pandas as pd
pd.DataFrame(car_dict).transpose().sort_index()

To view the output on terminal they way you requested,

for index, row in pd.DataFrame(car_dict).transpose().sort_index().iterrows():
    print('{},{},{}'.format(index, row['usa'], row['uk']))

will print this out:

audi,523487,456879
benz,876456,965471
bmw,754235,543298

Upvotes: 0

zedfoxus
zedfoxus

Reputation: 37129

You could do this:

car_dict= {
'benz': {'usa':876456, 'uk':965471},
'audi' : {'usa':523487, 'uk':456879},
'bmw': {'usa':754235, 'uk':543298}
}

cars = []
for car in car_dict:
    cars.append('{},{},{}'.format(
        car,
        car_dict[car]['usa'],
        car_dict[car]['uk']
    ))
cars = sorted(cars)

for car in cars:
    print(cars)

Result

audi,523487,456879
benz,876456,965471
bmw,754235,543298

Explanation

Loop through each car and store the model, USA number and UK number in a list. Sort the list alphabetically. List it.

Upvotes: 1

Related Questions