Reputation: 23
a= {'bana':3, 'hello':2, 'clue':7, 'an':1,'sad':3}
b=list(a.keys())
c=list(a.values())
sorted(c,reverse=True)
x=sorted(c, reverse=True)
print(x)
print(b)
d=[]
for i in x:
for z in b:
if a[z] == i:
l= str(i) +z
d.append(l)
b=sorted(d, reverse=True)
print(d)
hello, I have this code above. Whenever I print out d, I get:
['7clue', '3sad', '3bana', '3sad', '3bana', '2hello', '1an']
is there anyhow I can make it so that it is
['7clue', '3sad', '3bana', '2hello', '1an']
so it doesn't have that repeated 2 entries? Thanks
Upvotes: 0
Views: 75
Reputation: 52
Also, this should work:
a= {'bana':3, 'hello':2, 'clue':7, 'an':1,'sad':3}
b=list(a.keys())
x=sorted(list(a.values()), reverse=True)
d=[]
for i in range(len(x)):
d.append(str(x[i])+b[i])
print(d)
Upvotes: 0
Reputation: 5373
How about:
In [10]: b = [str(v)+k for k, v in zip(a.keys(), a.values())]
In [11]: b
Out[11]: ['3sad', '1an', '3bana', '2hello', '7clue']
In [12]: sorted(b, key = lambda m: int(m[0:1] ))
Out[12]: ['1an', '2hello', '3sad', '3bana', '7clue']
In [13]: sorted(b, key = lambda m: int(m[0:1] ), reverse=True)
Out[13]: ['7clue', '3sad', '3bana', '2hello', '1an']
?
Upvotes: 0
Reputation: 304137
This is the unique_everseen recipe from the itertools docs
from itertools import ifilterfalse,
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
L = ['7clue', '3sad', '3bana', '3sad', '3bana', '2hello', '1an']
res = list(unique_everseen(L))
If order doesn't matter, you can of course just use
L = list(set(L))
Upvotes: 0
Reputation: 21914
There are a couple ways of doing it, but I think this would be the most efficient so long as ordering doesn't matter:
>>> a = ['7clue', '3sad', '3bana', '3sad', '3bana', '2hello', '1an']
>>> list(set(a))
['1an', '2hello', '7clue', '3bana', '3sad']
If order does matter, then you can do this with a simple list comp:
>>> def remove_dups(a):
... seen = set()
... seen_add = seen.add
... return [ x for x in a if x not in seen and not seen_add(x)]
...
>>> remove_dups(['7clue', '3sad', '3bana', '3sad', '3bana', '2hello', '1an'])
['7clue', '3sad', '3bana', '2hello', '1an']
Upvotes: 1
Reputation: 1234
There may be a better way, but I've found using set() works well enough for most of what I do. For example, set(d). If you'd like the type to stay a list, you could use list(set(d)).
Upvotes: 0