0
d = {
    0:{1,2,3},
    1:{567},
    2:{2,3,5,8},
    3:{4,5,7,9},
    4:{6,7,8}
    }

I would like to compare the value of the first k-v pair with the key of the next k-v pair.

Example: To check if 1 exists in {1,2,3} or 2 exists in {567} If it does exist then I would like to delete the k that exists in the value.

Output should look like:

d = {
    0:{1,2,3},
    2:{2,3,5,8}
    }

I have tried using dictionary iterators with various permutations and combinations, but with no result. What would be the best way to achieve the result?

TheTank
  • 495
  • 2
  • 9
  • 21
  • Please explain the problem in detail. according to what i understand the output should be d = { 0:{1,2,3}, } because 1 is not in any of them . ***is this the output you expect –  Jun 23 '19 at 04:46

3 Answers3

0

Python dictionary are not ordered, so I'm not sure you can really speak of "next" of "previous" here. Using a pandas Series would be more appropriate.

However, you can still iterate over the keys and define this as your order.

previous = {}
dict_items = list(d.items())
for k,v in dict_items:
    if k in previous:
        del d[k]
    previous = v

EDIT: to make sure the keys are in the correct order, changing dict_items with:

dict_items = sorted(d.items(),key=lambda x:x[0])

would do it

Nakor
  • 1,484
  • 2
  • 13
  • 23
  • If you do this with an [`OrderedDict`](https://docs.python.org/3/library/collections.html?highlight=ordereddict#collections.OrderedDict) I guess you get exactly what @TheTank asked for? – André Laszlo Jun 22 '19 at 21:44
  • My goal is to try and find a solution without using third-party packages. In your answer, you are checking if the key exists in an empty dictionary, I'm not sure how that helps in the comparison. Please elaborate? – TheTank Jun 22 '19 at 21:44
  • 1
    Given that his dictionary keys are all integers, the keys do have an order. The first key is the smallest key, the second key is the second smallest key, etc... The correct ordering of the keys is `sorted (d.keys())` – Toothpick Anemone Jun 22 '19 at 21:44
  • Well, dictionary keys are in the same order than the order you inserted the keys. So if you have integer keys, it might not be in numeric order. I was not sure what order you were refering to. But then, Toothpick Anemone is right, sorting by the key would work. – Nakor Jun 22 '19 at 21:49
  • 1
    @Nakor that depends on your Python version though, see [this answer](https://stackoverflow.com/a/40007169/98057) for details. @TheTank [`OrderedDict`](https://docs.python.org/3/library/collections.html?highlight=ordereddict#collections.OrderedDict) is not third-party, it is part of the standard library so you just need to import it! :) – André Laszlo Jun 22 '19 at 21:53
  • @André Laszlo: I didn't know that, that's interesting – Nakor Jun 22 '19 at 21:56
0

Guessing by your example and requirement, you're on Python 3.6+, where dicts keep insertion orders. You can do:

In [57]: d = { 
    ...:     0:{1,2,3}, 
    ...:     1:{567}, 
    ...:     2:{2,3,5,8}, 
    ...:     3:{4,5,7,9}, 
    ...:     4:{6,7,8} 
    ...:     }                                                                                                                                                                                              

# Get an iterator from dict.keys
In [58]: keys_iter = iter(d.keys())                                                                                                                                                                         

# Get the first key
In [59]: first_key = next(keys_iter)                                                                                                                                                                        

# Populate output dict with first key-value
In [60]: out = {first_key: d[first_key]}                                                                                                                                                                    

# Populate out dict with key-values based on condition by
# looping over the `zip`-ed key iterator and dict values 
In [61]: out.update({k: d[k] for k, v in zip(keys_iter, d.values())
                     if k not in v})                                                                                                                         

In [62]: out                                                                                                                                                                                                
Out[62]: {0: {1, 2, 3}, 2: {2, 3, 5, 8}}
heemayl
  • 39,294
  • 7
  • 70
  • 76
0

It took me awhile to figure out what you wanted. Below, I have re-worded your example:

    EXAMPLE:

    Suppose the input dictionary is as follows:
       0:{1,2,3},    
       1:{567},      
       2:{2,3,5,8},  
       3:{4,5,7,9},  
       4:{6,7,8}    

    We have...

          key of 0:{1,2,3}  is 0
        value of 0:{1,2,3} is {1,2,3}

          key of 2:{2,3,5,8} is 2
        value of 2:{2,3,5,8} is {2,3,5,8}

    We execute code similar to the following:

    if key of 1:{567} in value of 0:{1,2,3}: 
    # if 1 in {1,2,3}:    
        delete 1:{567}

    if key of 2:{2,3,5,8} in value of 1:{567}:
    # if 2 in {567}: 
        delete 2:{2,3,5,8}

    and so on...    
    """

The following code should accomplish your goal:

def cleanup_dict(in_dict):  

    # sort the dictionary keys
    keys = sorted(indict.keys())

    # keys_to_delete will tell us whether to delete
    # an entry or not
    keys_to_delete = list()

    try:
        while True:
            prv_key = next(keys)
            nxt_key = next(keys)
            prv_val = in_dict[prv_key]
            if (nxt_key in prv_val):
                keys_to_delete.append(nxt_key)
    except StopIteration:
        pass 

    for key in keys_to_delete:
        del in_dict[key]            
    return
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42