0

preferences_dictionary = {1: [4, 2, 1, 3],2: [4, 3, 1, 2],3: [4, 3, 1, 2],4: [1, 3, 4, 2],5: [2, 3, 4, 1],6: [2, 1, 3, 4]}

Above is the preferences_dictionary and i need to fetch the the first value which is at position 0 for all the keys i.e most preferred no. in case of the list shown above it should be 4, as keys 1,2,3 prefer 4 over rest in the values.

Code that i used, but it is not overwriting the value:

preferences_dictionary = {1: [4, 2, 1, 3],2: [4, 3, 1, 2],3: [4, 3, 1, 2],4: [1, 3, 4, 2],5: [2, 3, 4, 1],6: [2, 1, 3, 4]}

def plu (preferences): sortedlist=sorted(preferences,reverse=True)

firstElementDict={}
for agent, sortedlist in firstElementDict.items():
    firstElementDict=sortedlist[0]
print(firstElementDict)
Ash
  • 9
  • 3
  • `from collections import Counter` `Counter(i[0] for i in preferences_dictionary.values()).most_common(1)[0][0]`… – deceze Jan 13 '22 at 15:01
  • @deceze i am not allowed to import any libraries like collections in such case – Ash Jan 13 '22 at 15:04
  • Fine, but even leaving out `Counter`, this example should demonstrate how you can "flatten" the complex dict into a simple list of "first values". Then it's just about finding the most common item in that list, which [shouldn't be hard…](https://stackoverflow.com/questions/1518522/find-the-most-common-element-in-a-list) – deceze Jan 13 '22 at 15:25

0 Answers0