Home > OS >  How to unpack only values from nested dict in for loop
How to unpack only values from nested dict in for loop

Time:11-23

I have the following code

mydict = {
    "key": {
        "k1": "v1",
        "k2": "v2",
    }
}
for k, (v1, v2) in mydict.items():

v1 and v2 actaully equals to k1 and k2, is there a way to extract v1 and v2 with any unpacking syntax?

I tried to search for unpacking syntax but found nothing

CodePudding user response:

No need to complicate on trying to unpack values. Here is a workaround

for k, (v1, v2) in mydict.items():
    print("Access the values for the key:", k, "--->", mydict[k][v1], mydict[k][v2])

output:

Accessing the values for the key: key ---> v1 v2

CodePudding user response:

It is possible like this:

mydict = {
    "key": {
        "k1": "v1",
        "k2": "v2",
    }
}

for v1, v2 in mydict.popitem()[1].values():
    print(v1, v2)
  • Related