简体   繁体   中英

Remove records from a dictionary of list

I want to delete records from a dictionary of list:

data{'key1':[value1,value2,value3,value4]
     'key2':[value1,value2,value3,value4]
     'key3':[value1,value2,value3,value4]}

how to delete all value2 in all keys?

data = {
           'key1':['value1','value2','value3','value4'],
           'key2':['value1','value2','value3','value4'],
           'key3':['value1','value2','value3','value4']
        }

for v in data.values():
  if 'value2' in v:
    v.remove('value2')
print(data)

There are multiple ways to delete records from a list for given dict.

data = {
       'key1':['value1','value2','value3','value4'],
       'key2':['value1','value2','value3','value4'],
       'key3':['value1','value2','value3','value4']
    }

Using remove method:

for keys, values in data.items():
    if 'value2' in values:
        data[keys].remove('value2')

Using pop method:

for keys, values in data.items():
    if 'value2' in values:
        values.pop(values.index('value2'))

Using del keyword:

for keys, values in data.items():
    if 'value2' in values:
        del values[values.index('value2')]

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