Home > Blockchain >  Python dictionary where values are lists, how to remove Xth item from every list value
Python dictionary where values are lists, how to remove Xth item from every list value

Time:08-25

I have dictionary in the form of:

dict_one =  { key2: [val1, val2, val3], key2: [val1, val2, val3] }

I want to remove 'val3' from every element in the dictionary. I believe this should be possible via a for loop but I can't seem to get it correct. I've tried the following:

for lst in dict_one:
    dict_one.pop(dict_one[lst][2])

This is intended, I believe, to remove both key and value. It returned a 'keyerror' error message. dict_one.remove() is clearly not going to work as it's meant for lists. It seems like what I'm trying to do should be relatively simple but I seem to be missing something.

(FYI, it seems like if I only wanted to delete a subset of the 'val3' items, I could follow the approach here: Remove element in dictionary of lists)

CodePudding user response:

First, to remove an item from a list:

l = [val1, val2, val3]
l.remove(val3)

Now looping through lists in dictionary:

dict_once = {key1: [val1, val2, val3], key2: [val1, val2, va3]}
for inner_list in dict_one.values():
    inner_list.remove(val3)

Or, looping through using keys:

for key in dict_one:
    dict_one[key].remove(val3)

CodePudding user response:

To get a specific item from list of dictionary:

for lst in dict_one:
    print(dict_one.get(lst)[item_num])

to modify an entry:

for lst in dict_one:
    dict_one[lst] = new_value
    print(dict_one.get(lst))

The changes you wanted to your lists:

dict_one =  { 'key2': ['val1', 'val2', 'val3'], 'key3': ['val1', 'val2', 'val3'] }

for lst in dict_one:
    dict_one[lst] = dict_one.get(lst)[:-1]
    print(dict_one.get(lst))

CodePudding user response:

One way using dict comprehension:

dict_one = {'key2': ['val1', 'val2', 'val3'], 'key3': ['val1', 'val2', 'val3']}
dict_two = {k: v[:-1] for k, v in dict_one.items()}
print(dict_two)

Output:

{'key2': ['val1', 'val2'], 'key3': ['val1', 'val2']}

CodePudding user response:

dict_one = {"key2": ["val1", "val2", "val3"], "key3": ["val1", "val2", "val3"]}
for lst in dict_one:
    dict_one[lst] = dict_one.get(lst)[:-1]
print dict_one
  • Related