-4

How do I delete a specific element of each dictionary item?

Given the following example, I want to delete 2nd element in key1, key2 and key3.

data{'key1':[value1 ,"abc" ,value3, value4]
     'key2':[value1 ,"def" ,value3, value4]
     'key3':[value1 ,1 ,value3, value4]}

So it should become:

Input: 2
Output: 
data{'key1':[value1,value3,value4]
     'key2':[value1,value3,value4]
     'key3':[value1,value3,value4]}

frankish
  • 6,738
  • 9
  • 49
  • 100
nputin
  • 1
  • 2
  • Could you be more specific ? – han solo Apr 13 '19 at 15:03
  • Hi, nputin! Welcome to the community. We are more than happy to see you here, all set to contribute for the first time. Your question seems a bit confusing, what is it that you want to delete in that dictionary? For information on how to ask questions, follow this link: https://stackoverflow.com/help/how-to-ask – nikhilbalwani Apr 13 '19 at 15:08
  • I have rewritten it – nputin Apr 13 '19 at 15:57

2 Answers2

1

From your example I guess you mean similar values instead of similar indices.

Checkout this answer if that's the case: Removing Duplicates From Dictionary

Note that Python's dictionaries "values()" method runs in O(n), so the most voted solution will have a O(n^2) complexity, where n is the number of items in the original dictionary.

If that's enough for you, your code will look something like

data = {'key1':[1,2,3,4],
     'key2':[1,2,3,4],
     'key3':[1,2,3,4]}

result = {}

for key,value in data.items():
    if value not in result.values():
        result[key] = value

At the end, 'result' will have the dictionary without duplicates.

0
for value in data.values():
    del value[index]

?

jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • it doesn't work ValueError: cannot delete array elements – nputin Apr 13 '19 at 15:59
  • 1
    Itwill work it the dictionary elements are actually lists, but it looks like you have some other sequence type that does not support item deletion. – jsbueno Apr 13 '19 at 16:35