4

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)
wwii
  • 23,232
  • 7
  • 37
  • 77
imprivate
  • 41
  • 1
  • 2
  • Possible duplicate of [Delete an element from a dictionary](http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary) – Harshdeep Sokhey Jan 24 '17 at 19:38

3 Answers3

5

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.


P.S.: 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).

Kevin Wang
  • 2,673
  • 2
  • 10
  • 18
1

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

for v in G.values():
    _ = v.pop('noone', None)
wwii
  • 23,232
  • 7
  • 37
  • 77
0

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}}
Michael Goerz
  • 4,300
  • 3
  • 23
  • 31