Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have a dictionary with a fixed format like:

dict = {1111: {'vehicle_id': 1111, 'vehicle_capacity': 800},

        3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}}

The output I would like to get is:

list_dict1 = [{1111: {'vehicle_id': 1111, 'vehicle_capacity': 800}]

list_dict2 = [{3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}]

The format of dict can't be changed, I tried to get it by calling the keys (1111 and 3333), but the output will show without the keys. Anyone can help me with how to do it?

1 Answer

0 votes
by (36.8k points)

The one-liner solution:

>>> d = {1111: {'vehicle_id': 1111, 'vehicle_capacity': 800},

         3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}}

>>> lst = [dict([(key, value)]) for key, value in d.items()]

[{1111: {'vehicle_id': 1111, 'vehicle_capacity': 800}}, {3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}}]

So dict.items() is a simple way to access the dictionary items in an iterable format. Then by using list comprehension, it's up to your imagination how you transform it.

Note that dict is a reserved keyword in Python, it's a class constructor to create dictionaries. It's better not to shadow its binding in your code.

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

Browse Categories

...