itjcms18
itjcms18

Reputation: 4353

removing a certain element from a list in a dictionary's value

not sure why i can't figure this out. here is my dictionary:

begin = {'kim': ['a', 'c', 'nope'], 'tom': ['b', 'd', 'e', 'nope', 'nope']}

i'm trying to remove a specific element from the list in the dictionary's values. the value i want to remove is 'nope'. therefore, my desired output would be:

begin = {'kim': ['a', 'c'], 'tom': ['b', 'd', 'e']}

here is what i tried and it didn't seem to work

for i in begin:
    for a in begin.get(i):
        if a == 'nope':
            del a
print begin 

any help would be greatly appreciated. seems basic but just can't seem to get it

Upvotes: 0

Views: 55

Answers (4)

Jan Spurny
Jan Spurny

Reputation: 5537

What you actually want is to remove the value from a list which happens to be inside a dictionary. You could think that list.remove('nope') may work, but it would remove only one 'nope' from each list. You may use either comprehension or filter function to filter out nopes For example:

# python 2.x - comprehension
new_dictionary = dict(
    (key, [v for v in value if v != 'nope'])
    for key, value in begin.iteritems()
)

# python 2.x - filter
new_dictionary = dict(
    (key, filter(lambda v: v != 'nope', value))
    for key, value in begin.iteritems()
)

# python 3.x - comprehension
new_dictionary = {
    key: [v for v in value if v != 'nope']
    for key, value in begin.items()
}

# python 3.x - filter
new_dictionary = {
    key: list(filter(lambda v: v != 'nope', value))
    for key, value in begin.items()
}

Upvotes: 1

dawg
dawg

Reputation: 104092

One line dict comprehension with filter:

>>> {k: filter(lambda s: s!='nope', v) for k, v in begin.items()}
{'kim': ['a', 'c'], 'tom': ['b', 'd', 'e']}

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114078

for person in begin:
    while "nope" in begin[person]:
          begin[person].remove("nope")

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239653

Just filter out nopes from the lists, with list comprehension, like this

for key in begin:
    begin[key] = [item for item in begin[key] if item != 'nope']

Or you can completely recreate the begin dictionary, with dictionary comprehension like this

begin = {key:[item for item in begin[key] if item != 'nope'] for key in begin}

Upvotes: 3

Related Questions