Reputation: 1596
I am trying to get the first K items from a dictionary. My code is given below.
d= dict([(1, 2.0), (2, 0.0), (3, 3.0), (4, 0.0), (5, 4.0), (6, 0.0), (7, 0.0), (8, 0.0), (9, 0.0), (10, 3.0), (11, 3.0), (12, 2.0), (13, 0.0), (14, 0.0), (15, 0.0), (16, 0.0), (17, 0.0), (18, 0.0)])
d
{1: 2.0, 2: 0.0, 3: 3.0, 4: 0.0, 5: 4.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0, 10: 3.0, 11: 3.0, 12: 2.0, 13: 0.0, 14: 0.0, 15: 0.0, 16: 0.0, 17: 0.0, 18: 0.0}
dict(islice({k:v for k,v in sorted(d.items(), key=lambda item : item[1], reverse=True)},5))
Traceback (most recent call last): File "", line 1, in TypeError: cannot convert dictionary update sequence element #0 to a sequence
I have hard time understanding what went wrong. Because similar code works without any issue
dd
{'d': 4, 'c': 3, 'b': 2, 'a': 1}
dict(islice(dd.items(),2))
{'d': 4, 'c': 3}
Upvotes: 0
Views: 24
Reputation: 60974
islice
treats it's first argument as an iterator. When you iterate over a dictionary, you only iterate over the keys, not the values:
d = {'a': 1, 'b':2, 'c':3}
print(list(islice(d, 1))) # ['a']
So you just need to remove the dictionary comprehension around sorted
, since the items it produces can be consumed by dict
to make a new dictionary
dict(islice(sorted(d.items(), key=lambda item : item[1], reverse=True),5))
# {5: 4.0, 3: 3.0, 10: 3.0, 11: 3.0, 1: 2.0}
Upvotes: 1