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

Question:

#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]:
        if j == "J" or j == "Q" or j == "K":
            all_cards.append(10)
        elif j =="A":
            all_cards.append(11)
        else:
            all_cards.append(j)
print(all_cards)

without doing this, can we call the value corresponding to the key inside the nested dictionary in a for loop?

#output needed

all_cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Asked By: Anurad

||

Answers:

You can use this snippet:

values = list(set(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 [10, 10, 10, 11]. We then combine these two lists and use set() to remove duplicates.

Answered By: Salad

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)
Answered By: flakes

what if there is another dictionary inside the nested one?

card_values = {
    "normal": [2, 3, 4, 5, 6, 7, 8, 9, 10],
    "suited": {"J":10, "Q":10, "K":10, "A":11, "Q": {"a": 13}}
}
all_cards = sorted(
    set(card_values["normal"])
    | set(card_values["suited"].values())
    | set(card_values["suited"]["Q"].value()))

print(all_cards)

how do I get this code to work?

Answered By: Anurad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.