python - Dictionary with lists as values - find longest list -
I have a dictionary where there are a price list after removing a duplicate, I need to know which key The long list is in the form of value if I find the longest list then it will not work because there can be many duplicates in it. I have tried many things, but nothing is far away from not being right.
d = your dictionary of max_key = max (d, key = lambda x: lane) (Set (d [x])) # Here is the short version I explain .... Maximum (# function which grabs the greatest value D, # is the dictionary, it repeats and catches through every key Is ... key = # this overlays the default behavior of maximum lambda x: Definition of lambda to handle new behavior for maximum lane (# Of the length ... set (containing # set (no duplicate) d [x] # key defined by the keyword `x`))
code After the maximum
, the dictionary goes through the keys (which happens through a dictionary, by for x in dict: print x
each key is Dict
) This key will return that it finds it to achieve the highest result when it comes to our State applies the function to maintain (which is that lambda
) key =
. You can literally do anything here, this is the beauty of it, however, if you want the key and value, then you might be able to do something like this ....
d = # Your dictionary max_key, max_value = max (d.items (), key = lambda k, v: lane (set (v))) # this does not work, see my note on bottom
This is different because d
, which is a dictionary, we pass d.items ()
, which is of d
Tuples made of keys and values For example:
d = {"foo": "bar", "spam": ['green', 'eggs', 'and', 'ham']} Print (d. Item) # [("Foo", "bar"), # ("spam", ["green", "egg", "and", "ham"])]
< / Pre>We are not looking at a dictionary anymore, but all the data is still there! This has made it easier to deal with the use of the unpack statement I used:
max_key, max_value =
. It works the same way as you didWIDTH, HEIGHT = 1024, 768
.Max
still works normally, it repeats through the new list created with thed.items ()
and returns those values to itskey
returns the function (lambda k, v: lane (set (v))
). You will also see that we do not have to dolen (set of [d]), instead it is working directly on
v
, becaused .items ()
has already created thed [k]
value, and usingLambda K, V
to specify that key, the same unpack The statement is using the value ofk
andv
.Magic! Magic does not work, apparently I have not eaten a lot here Was, and
lambda No, in fact, you can open your own values instead, do: max_key, max_value = max (d.items (), key = lambda X: len (set (x [1]))
Comments
Post a Comment