-3

I am a total beginner on python and wondering if this is possible?

businessideas = {
"DeliDelivery": ['bread'],
"Ikea": ['sofa','table'],
'Volvo': ['car','window'],
'saab' : ['window']
}




carkeywords = ['car', 'engine']
furniturekeywords = ['sofa', 'bookshell']
bakerykeywords = ['bread', 'flour', 'cookies']

carkeywords_competitors = []
furniturekeywords_competitors = []
bakerykeywords_competitors = []

I want to create a function that puts every dictionary-key in a competitors list if they have a common value. So for an example the key Ikea has the elements sofa and table. Then the function should see that the value sofa is a duplicate to of furniturekeywords elements. Then the funtion should put the key Ikea in the list furniturekeywords_competitors. If it would have the same value as carkeywords the function would have put the key in carkeywords_competitors.

  • Welcome to StackOverflow. Yes, this is possible. However, your *actual* problem is not clear. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your code and accurately describe the problem. – Prune Nov 17 '16 at 22:25
  • [Calculating the similarity of two lists](http://stackoverflow.com/questions/6709693/calculating-the-similarity-of-two-lists) – Tadhg McDonald-Jensen Nov 17 '16 at 22:26
  • Possible duplicate of [How can I compare two lists in python and return matches](http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches) – Tadhg McDonald-Jensen Nov 17 '16 at 22:31

1 Answers1

2

So the task is to find those sets of items that are not disjoint with the keywords. This can be done with sets and the isdisjoint method:

businessideas = {
"DeliDelivery": ['bread'],
"Ikea": ['sofa','table'],
'Volvo': ['car','window'],
'saab' : ['window']
}

carkeywords = ['car', 'engine']

def competitors(ideas, keywords):
   keywords = set(keywords)
   return [k for k,v in ideas.items() 
           if not keywords.isdisjoint(v)]

carkeywords_competitors = competitors(businessideas, carkeywords)

results in:

>>> carkeywords_competitors
['Volvo']

Note that if the elements of the lists weren't hashable, but did have equality defined for them, any(i in kwds for i in v) would be what I would use. (if they didn't have equality the task would be impossible and the only option would be False) But they are hashable as they are strings. So not set(v).isdisjoint(kwds) beats that.

Dan D.
  • 73,243
  • 15
  • 104
  • 123