Append Element To Smallest List In Dictionary Of Lists
I have a dictionary of lists for which I want to add a value to a particular list... d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]} I want
Solution 1:
>>> d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]}
>>> smallest = min(d, key=lambda k: len(d[k]))
>>> d[smallest].append(2)
>>> d
{'a': [4, 2], 'c': [4, 3], 'b': [3, 4], 'e': [4, 2], 'd': [4, 3], 'g': [4], 'f': [4]}
Solution 2:
How about:
d[gsl(d)[0]].append(2)
gsl(d)
gets the list of keys with minimal length, 0
gets the first one, and then we get the list at that key and append 2
to it.
Solution 3:
The problem with your answer is that, after inserting the element in 'e', it is not anymore part of the "keys with minimum length lists", so on the next iteration it will return ['f', 'g'].
One quick fix to it is to break the loop, like this:
for i in d:
if gsl(d)[0] == i:
d[i].append(2)
break
But this is a very inefficient way of doing what you want, and will fail if d is empty.
Solution 4:
If you're using python 2.7 or newer, you can use a view for this:
>>> d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]}
>>> min(d.viewitems(), key=lambda (k, v): len(v))[1].append(2)
>>> d
{'a': [4, 2], 'c': [4, 3], 'b': [3, 4], 'e': [4, 2], 'd': [4, 3], 'g': [4], 'f': [4]}
If you're using an older version, you can use iteritems:
>>> d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]}
>>> min(d.iteritems(), key=lambda (k, v): len(v))[1].append(2)
>>> d
{'a': [4, 2], 'c': [4, 3], 'b': [3, 4], 'e': [4, 2], 'd': [4, 3], 'g': [4], 'f': [4]}
Post a Comment for "Append Element To Smallest List In Dictionary Of Lists"