I have two dict with different keys. I would like to combine both keys into a list or something so that I can iterate over. However the order is important because at some places of the script I need to preserve the order for other calculations via enumerate()
Here is a small example of what I am trying to do:
ns.keys()
Out[1]: dict_keys([108])
no.keys()
Out[2]: dict_keys([120, 124, 126, 127, 112, 114, 115, 117, 118, 135, 132, 133, 109, 130, 111, 129, 136])
I want to iterate over both of them like following:
for key in [ns.keys() | no.keys()]:
print(key)
Out[3]: {129, 130, 132, 133, 135, 136, 108, 109, 111, 112, 114, 115, 117, 118, 120, 124, 126, 127}
The order is important because, I also want to do following:
for i, key in enumerate([ns.keys() | no.keys()]):
print(i, key)
I want the order of [ns.keys() | no.keys()]
to be first ns.keys()
then no.keys()
. In this example, it should be:
[108, 120, 124, 126, 127, 112, 114, 115, 117, 118, 135, 132, 133, 109, 130, 111, 129, 136]
Following works list(ns.keys()) + list(no.keys())
, any other idea?
Just unpack dict keys within a list for iteration:
[*ns.keys(), *no.keys()]