简体   繁体   中英

Removing key/value pair from Dictionary in Python

I'm quite a beginner with python.

I'm trying to remove all the 'noone: 0' from this dictionary, so it will look the same as below but without any of the 'noone: 0':

G = {'a': {'b': 10, 'c': 8, 'd': 3, 'noone': 0, 'e': 3}, 'f': {'g': 7, 'c': 5, 'h': 5, 'i': 2, 'j': 4, 'noone': 0, 'l': 2}}

I searched and found all the ways I should be implementing it, but cannot find a method that works. I tried this to no avail:

for i in G:
    if str(G[i]) == 'noone':
        G.pop('noone', None)

I believe this would do what you want.

for i in G:
    if 'noone' in G[i]:
        G[i].pop('noone')

What you have here (G) is indeed a dictionary, but more specifically, it's a dictionary whose values are also dictionaries. thus, when we iterate through all the keys in G ( for i in G ), each key's corresponding value ( G[i] ) is a dictionary. You can see this for yourself if you try running:

for i in G:
    print(G[i])

So what you really want to do is pop from each dictionary in G. That is, for each G[i], you want to remove 'noone' from those "sub"-dictionaries, not the main top one.


PS: if you really want to take advantage of python's convenience, you can even write simply

for i in G:
    G[i].pop('noone', None)

By using the second argument into pop , you don't even have to check to see if 'noone' is a key in G[i] first because the pop method will not raise an exception. (if you tried this two-liner without the second argument, you'd get an error for all sub-dicts that don't have 'noone' in them).

Iterate over the values and pop the key from each value:

for v in G.values():
    _ = v.pop('noone', None)

I would go with dictionary comprehension:

>>> G = {'a': {'b': 10, 'c': 8, 'd': 3, 'noone': 0, 'e': 3}, 'f': {'g': 7, 'c': 5, 'h': 5, 'i': 2, 'j': 4, 'noone': 0, 'l': 2}}
>>> {k1: {k2: v2 for (k2, v2) in v1.items() if k2 != 'noone'} for k1, v1 in G.items()}
{'f': {'g': 7, 'c': 5, 'j': 4, 'h': 5, 'i': 2, 'l': 2}, 'a': {'b': 10, 'e': 3, 'd': 3, 'c': 8}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM