1

Given is a list with unsorted indices in a list of length n. Each element of the list is only once contained. So the list looks like this

L = [13, 145, 70001, 34, ..., 533]

Also given is a dictionary d which numerical values as key. All values are element {0,1}. Like

d = {
        "[some data]" : 0,
        "[some data]" : 1,
        "[some data]" : 1,
        "[some data]" : 1,
        ...
        "[some data]" : 0
    }

There are a lot more entries in the dictionary d then in the list L.

What I want to do is deleting data from the dictionary for each position (index) from L if it is a 0.

The problem that I see while proceeding it that after the each deletion the indices need to be shifted since the position within dictionary is changing. Which is quiet inefficient regarding on a large number of items in L. There must be an efficient way of proceeding this task.

Any ideas and suggestions are highly appreciated!

martineau
  • 119,623
  • 25
  • 170
  • 301
Jürgen K.
  • 3,427
  • 9
  • 30
  • 66
  • 2
    What have you tried? You gotta do it yourself first before asking for help. – Mike Tung Apr 27 '19 at 20:07
  • 1
    A few things missing in your question: 1) An example dictionary, 2) an example list, 3) Expected output 4) Your attempt to solve the problem. – amanb Apr 27 '19 at 20:10
  • 1
    It is not clear to me what you are trying to accomplish. Can you provide example input with corresponding output? Note, *dictionaries don't have indices* – juanpa.arrivillaga Apr 27 '19 at 20:11
  • 1) look d, key value is irrelevant 2) look at L 3) expected output is a dictionary without entries on position the following positions 13, 145, 70001, 34, ..., 533. 4) deleting data on position 13, than shifting all indices in L to the left. So the new L is 144, 70000, 33,...532, 4 – Jürgen K. Apr 27 '19 at 20:28

3 Answers3

6

Note that you should not expect to be able to do this as most dictionary implementations are not ordered, but Python's is since 3.6 and a part of the spec in 3.7 - but onto the question.

We can use a dictionary comprehension with enumerate to make a new dictionary so we do not have to worry about the index shifting business that worries you.

L_ = set(L)
d = {k: v for i, (k, v) in enumerate(dict.items()) if i not in L_ and v}
modesitt
  • 7,052
  • 2
  • 34
  • 64
0

dictionary.keys() and dictionary.values() both return indexable lists in python 2

As @grooveplex notes, in python 3, you can wrap each one with list() for the same effect

Alec
  • 8,529
  • 8
  • 37
  • 63
0

I propose that instead of directly deleting the item, you update it with e.g. -1 and at the end you delete all -1 records

Pablo Henkowski
  • 197
  • 1
  • 6