Home > database >  how to convert a nested dictionary to a list, combine it with existing list and display results
how to convert a nested dictionary to a list, combine it with existing list and display results

Time:01-12

#nested dictionary

card_values = {
"normal": [2, 3, 4, 5, 6, 7, 8, 9, 10], 
"suited": {"J":10, "Q":10, "K":10, "A":11}
}

#code I wrote to try and iterate over the values

all_cards = []
for i in card_values:
    for j in card_values[i]:
        all_cards.append(j)
print(all_cards)

#output needed

all_cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

CodePudding user response:

You can use this snippet:

all_cards = card_values["normal"]   list(card_values["suited"].values())

this returns :

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

what each part of the code is doing: We are first getting [2, 3, 4, 5, 6, 7, 8, 9, 10] from the "normal" key in card_values. Then we are getting only the values from the "suited" key in card_values and then converting them to a list which leaves

CodePudding user response:

I would make a set to get the unique values and then sort it.

card_values = {
    "normal": [2, 3, 4, 5, 6, 7, 8, 9, 10],
    "suited": {"J":10, "Q":10, "K":10, "A":11}
}

all_cards = sorted(
    set(card_values["normal"])
    | set(card_values["suited"].values())
)

print(all_cards)
  • Related