I want 'to': ['learn', 'have', 'make'] I keep getting 'to': ['learn', 'have', 'learn', 'make']
CodePudding user response:
METHOD 1:
Here's the beginners, easy to get (probably inefficient) code:
dic = {'to': ['have', 'learn', 'learn', 'make']}
print(dic)
for i in dic['to']:
for j in dic['to'][dic['to'].index(i) 1:]:
if i == j:
dic['to'].remove(j)
print(dic)
# OUTPUT:
# {'to': ['have', 'learn', 'learn', 'make']}
# {'to': ['have', 'learn', 'make']}
It works by checking all elements after an element, for every element in the list.
METHOD 2:
Using OrderedDict from collections (one liner):
from collections import OrderedDict
dic = {'to':['learn', 'have', 'make', 'learn']}
print(dic)
dic['to'] = list(OrderedDict.fromkeys(dic['to']))
print(dic)
#SAME OUTPUT AS BEFORE
CodePudding user response:
You can simply convert your list to a set and back to list.
x = {'to': ['learn', 'have', 'learn', 'make']}
for key, value in x.items():
x[key] = list(set(value))
Output:
{'to': ['learn', 'have', 'make']}
Set is a collection of unique elements. So passing your list to set() function returns a set of unique elements of that list, which you can then pass onto the list() function, to get the list back.
