How to delete a element from nested dictionary?

I have a dictionary that like this :

card_pool = {
    'ace' : [1,11], 
    '2' : 2,
    '3' : 3,
    '4' : 4,
    '5' : 5,
    '6' : 6,
    '7' : 7,
    '8' : 8,
    '9' : 9,
    '10' : 10,
    'J' : 10,
    'Q' : 10,
    'K' : 10,
}

l_card_pool = {}
l_card_pool['spade'] = card_pool
l_card_pool['clover'] = card_pool
l_card_pool['heart'] = card_pool
l_card_pool['diamond'] = card_pool

I wanted to delete a key-value pair of :

l_card_pool['spade']['ace']

So I used :

del l_card_pool['spade']['ace']

What I’ve expected of print(l_card_pool) is this :

{
'spade': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}, 
'clover': {'ace': [1, 11], '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}, 
'heart': {'ace': [1, 11], '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}, 
'diamond': {'ace': [1, 11], '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}
}

But I actually got this :

{
'spade': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}, 
'clover': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}, 
'heart': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}, 
'diamond': {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}
}

There is a way of deleting only l_card_pool['spade']['ace'] ?

Whole code is this :

card_pool = {
    'ace' : [1,11], 
    '2' : 2,
    '3' : 3,
    '4' : 4,
    '5' : 5,
    '6' : 6,
    '7' : 7,
    '8' : 8,
    '9' : 9,
    '10' : 10,
    'J' : 10,
    'Q' : 10,
    'K' : 10,
}

l_card_pool = {}
l_card_pool['spade'] = card_pool
l_card_pool['clover'] = card_pool
l_card_pool['heart'] = card_pool
l_card_pool['diamond'] = card_pool >create l_card_pool dictionary

print(l_card_pool) 

del l_card_pool['spade']['ace'] >What I used to delete a element from nested dictionary

print(l_card_pool)

>Solution :

All dicts l_card_pool[*] are the same dict. If you’re planning to mutate any of them, you need to copy them on creation, e.g.:

l_card_pool = {}
for suite in ('spade', 'clover', 'heard', 'diamond'):
    l_card_pool[suite] = card_pool.copy()

That creates a shallow copy of the dict. If for any reason, you’re planning to mutate e.g. l_card_pool['spade']['ace'] by removing elements from it, I’d suggest using deepcopy.

Leave a Reply