Reputation: 2738
I have a dictionary with a key and an item. Basically, keys keep people name and the values keep salary. What I want is that ordering items according to their frequency with the higher value.
d = {'name-1': 100, 'name-2':90, 'name-3': 80, 'name-1': 80}
print OrderedDict(sorted(d.items(), key=lambda t: t[1]))
So, the output should be ('name-1':100)
. Because, the occurrence is two in the dict and the salary is the highest.
I can only sort this dict. Could you please help me to get that result ?
Upvotes: 1
Views: 234
Reputation: 114118
as others have pointed out you cannot have duplicate keys in a dict... however you could easily use a list
#d = (('name-1', 100), ('name-2',90), ('name-3',80), ('name-1',80))
names = "name1,name2,name3,name1".split(",")
salaries = map(int,"100,90,80,80".split(","))
d = zip(names,salaries)
print max(d,key=lambda x:names.count(x[0])*1000+x[1])
#('name-1', 100)
print sorted(d,key=lambda x:names.count(x[0])*1000+x[1],reverse=True)
[('name-1', 100), ('name-1', 80), ('name-2', 90), ('name-3', 80)]
Upvotes: 3
Reputation: 19355
Have you tried creating that d
dict?
>>> d = {'name-1': 100, 'name-2':90, 'name-3': 80, 'name-1': 80}
>>> d
{'name-1': 80, 'name-2': 90, 'name-3': 80} # notice 'name-1' is only in there once.
>>>
If you try to create a second key with the same name in the dict, it will over write the value that was associated with that key. Every key is unique in a dict... If they weren't unique, dictionaries would no longer be near as useful.
You could create a nested tuples/lists if you need this sort of data structure... However, it will be far slower as finding a key will require iterating over all objects in the list:
d = (
('name-1', 100),
('name-2', 90),
('name-3', 80),
('name-1', 80),
)
Upvotes: 0
Reputation: 304503
One approach would be to use a dict, but store the values in lists for each key
>>> d = {'name-1': [100, 80], 'name-2':[90], 'name-3': [80]}
and then
>>> sorted(d, key=lambda x:max(d.get(x)), reverse=True)
['name-1', 'name-2', 'name-3']
Upvotes: 4