interstellar
interstellar

Reputation: 399

if key, value pair exist in a dictionary skip python

I have two variables that I want to add to a dictionary using collections.defaultdict(list) Here are the two variables:

score = [0, 5, 7, 7, 8, 7]
match = ['turtle', 'cat', 'horse', 'horse', 'dog', 'bear']

What I would like to do is to remove the key/value pairs that are already in the dictionary. Right now I am creating my dictionary using this method:

  scoring = collections.defaultdict(list)
  scoring[score].append(match)

However, this method gives me a dictionary like so:

dictionary = {0: ['turtle'], 5: ['cat'], 7: ['horse', 'horse', 'bear'], 8: ['dog']}

However, I only want horse to appear in the dictionary once. Is there anyway to prevent the additional of an identical key/value pair in a dictionary this way?

Upvotes: 2

Views: 1964

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

You can use a set() instead of a list for preserving the values:

>>> coring = defaultdict(set)
>>> for i,j in zip(score, match):
...     coring[i].add(j)
... 
>>> coring
defaultdict(<type 'set'>, {0: set(['turtle']), 8: set(['dog']), 5: set(['cat']), 7: set(['horse', 'bear'])})
>>> 

Since the set object doesn't preserve the order, if you care about the order of the items of the values, you can use an OrdereDict as the values container:

>>> from collections import defaultdict, OrderedDict
>>> coring = defaultdict(OrderedDict)
>>> 
>>> for i,j in zip(score, match):
...     coring[i][j]=None
... 
>>> coring
defaultdict(<class 'collections.OrderedDict'>, {0: OrderedDict([('turtle', None)]), 8: OrderedDict([('dog', None)]), 5: OrderedDict([('cat', None)]), 7: OrderedDict([('horse', None), ('bear', None)])})
>>> 
>>> coring[7]
OrderedDict([('horse', None), ('bear', None)])
>>> coring[7].keys()
['horse', 'bear']

Upvotes: 2

Iron Fist
Iron Fist

Reputation: 10951

If you wan to keep using lists instead of sets, then do filtering:

>>> d = defaultdict(list)
>>> for k,v in zip(score, match):
        if k not in d or v not in d[k]:
            d[k].append(v)


>>> d
defaultdict(<class 'list'>, {0: ['turtle'], 8: ['dog'], 5: ['cat'], 7: ['horse', 'bear']})

Upvotes: 1

Related Questions