This achieves exactly what you ask for, two list
s containing one dict
each (despite having a different order..)
let's walk through in an interactive python shell. set the variable first:
>>> test = {1111: {'vehicle_id': 1111, 'vehicle_capacity': 800}, 3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}}
>>> test
{3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}, 1111: {'vehicle_id': 1111, 'vehicle_capacity': 800}}
Now you can walk the keys in a for loop:
>>> for key in test:
... print(key)
...
3333
1111
What we now need is to generate the variable names of the lists you want to achieve dynamically. We may use vars()
for that. So let's enumerate
the key
s of the original dict
to get a sequence of numbers for each key
(you might want to check out zip
for similar things as well). The idea is to concatenate the base name of your lists, list_dict
, with a sequential integer, num
, to generate the variables dynamically. The key
in the for
loop can be used to set the key
of the dict
in each list
as well as access the original dict
to get and assign the corresponding values.
>>> for num, key in enumerate(test):
... vars()["list_dict" + str(num+1)] = [{key: test[key]}]
...
>>> list_dict1
[{3333: {'vehicle_id': 3333, 'vehicle_capacity': 4800}}]
>>> list_dict2
[{1111: {'vehicle_id': 1111, 'vehicle_capacity': 800}}]