What I am trying to do is delete the key value pairs out of a dictionary if the value is = 0. I seem not to be acheiving that so far.

Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [10, 0, 35, 45, 34, 0, 22, 0]
>>> keys = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']
>>> dictionary = dict(zip(keys, a))
>>> dictionary
{'Seven': 22, 'Six': 0, 'Three': 35, 'Two': 0, 'Four': 45, 'Five': 34, 'Eight': 0, 'One': 10}
>>> {i:dictionary[i] for i in dictionary if i!=0}
{'Seven': 22, 'Six': 0, 'Three': 35, 'Two': 0, 'Four': 45, 'Five': 34, 'Eight': 0, 'One': 10}
>>> del dictionary[key] if val=0
  File "<stdin>", line 1
    del dictionary[key] if val=0
                         ^
SyntaxError: invalid syntax
>>> if x in dictionary = 0 del dictionary[key]
  File "<stdin>", line 1
    if x in dictionary = 0 del dictionary[key]
                       ^
SyntaxError: invalid syntax
>>> if x in dictionary == 0 del dictionary[key]
  File "<stdin>", line 1
    if x in dictionary == 0 del dictionary[key]
                              ^
SyntaxError: invalid syntax
>>> 

How should I be attacking this?

>>> d={"key1":3,"key2":18,"key3":8}
>>> d["key2"]=0
>>> d
{'key3': 8, 'key2': 0, 'key1': 3}
>>> s=d.items()
>>> s
[('key3', 8), ('key2', 0), ('key1', 3)]
>>> for i in s:
...    if i[1]==0:
...       del d[i[0]]
... 
>>> d
{'key3': 8, 'key1': 3}

That way is a little unpythonic way to do it rrashkin.

d = {'Seven': 22, 'Six': 0, 'Three': 35, 'Two': 0, 'Four': 45, 'Five': 34, 'Eight': 0}
for k,v in d.items():
    if v == 0:
        del d[k]

print d
#--> {'Five': 34, 'Four': 45, 'One': 10, 'Seven': 22, 'Three': 35}

For both dictionary and list it's not so normal to use del.
Here create a new dictionary using dict comprehension,as you see no del.

>>> d = {'Seven': 22, 'Six': 0, 'Three': 35, 'Two': 0, 'Four': 45, 'Five': 34, 'Eight': 0}
>>> {k:v for k,v in d.items() if v != 0}
{'Five': 34, 'Four': 45, 'One': 10, 'Seven': 22, 'Three': 35}

Just to show the same with a list.

>>> lst = [1, 2, 0, 4, 0, 3, 0, 2, 0, 2]
>>> [i for i in lst if i != 0]
[1, 2, 4, 3, 2, 2]

that's what I was trying to do but stuffed it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.