0

I want to order some nested dictionaries to match the order of this list:

vehicle_type = ['Car', 'Bike', 'Bus']

This is currently what the nested dictionary looks like:

vehicles = {'2018': {'Bike': 2542, 'Bus': 37, 'Car': 33432}, '2012': {'Car': 68122, 'Bike': 164, 'Bus': 1653}, '2001': {'Car': 12127, 'Bus': 324, 'Bike': 4222}}

I have organised the outer keys which represent the years with:

ordered_dict = [(k, vehicles[k]) for k in sorted(list(vehicles.keys()))]

I'm just unsure on how I go through each year and organise their keys to the order of my vehicle_type list? I'm probably being dumb

1
  • 1
    Given a dict D with the right keys but arbitrary order, {key: D[key] for key in vehicle_type} would produce a new dict in the right order. Change to {key: D.get(key) for ... if some of the dicts might have missing keys (which this code would turn into explicit Nones). Commented May 5, 2021 at 0:18

2 Answers 2

2

We can use a dict comprehension to re-order your keys based on your input list.

new_vehicles = {key: {d: v.get(d) for d in vehicle_type} for key, v in vehicles.items()}

new_vehicles
#{'2018': {'Car': 33432, 'Bike': 2542, 'Bus': 37}, '2012': {'Car': 68122, 'Bike': 164, 'Bus': 1653}, '2001': {'Car': 12127, 'Bike': 4222, 'Bus': 324}}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly! Was so close by the methods I was trying haha
0

If you want a dict like

{'Bike': {'2001', 164, '2012', 4222, '2018', 2542}, 'Bus': {'2001', 324, 37, 1653, '2012', '2018'}, 'Car': {'2001', 33432, '2012', 68122, '2018', 12127}}

you should write something like

vehicles_by_type = {}
for year, vehicle_in_year in vehicles.items():
    for vehicle_type, x in vehicle_in_year.items():
        if not vehicle_type in vehicles_by_type:
            vehicles_by_type[vehicle_type] = {}
        vehicles_by_type[vehicle_type].update({year, x})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.