Nik.Birur Nik.Birur - 2 months ago 16
Python Question

List comprehensions Conversion

i started learning Python recently and i am facing difficulty converting the below piece of code into a list comprehension:

list = [] #An empty List
for key,value in defaultDict.items():#iterate through the default dict
for i in defaultDict[key]:#iterate through the list in the defaultDict
if i not in list:#If the item in the list is not present in the main list
list.append(i)#append it


Is it possible for me to even do it??Any help with this is much appreciated.

Answer

Very straightforward: use a nested list comprehension to get all is and a set to remove duplicates.

list(set([item for __, value in defaultDict.items() for item in value]))

Let's break it down:

  • [item for key,value in defaultDict.items() for item in value] is a nested list comprehension.
  • set(...) will remove all duplicates - the equivalent of if i not in list: list.append(i) logic you have
  • list(set(...)) will convert the set back to a list for you.
Comments