Home > OS >  Compare values of 1 dict and if they equal append to new list key which is equal to another dict las
Compare values of 1 dict and if they equal append to new list key which is equal to another dict las

Time:12-12

I have two dictionaries like: r= Number of word occurrences in Text they u Sorted them by asc firstly by values then keys w = Number of length of the words in text Sorted by asc firstly by values then keys

r = {
    'aday': 3,
    'day': 3,
    'ahaha': 1,
    'donat': 1,
    'kakaw': 1
} 

w = {
    'ahaha': 5,
    'donat': 5,
    'kakaw': 5,
    'aday': 4,
    'day': 3
}

I'm not good with loops, with dictionaries especially.

How can I do this: if max values of r are equal (aday and day equal to 3 ) I want to take key which is equal to the second dictionary w last item (day) so I want to take day in this case q.append(day).

Here is what I tried:

for ke,va in r.items():
    for da,ty in w.items():
        if va==ty:
          g.append(r[ke])
print(g)

Thank you

CodePudding user response:

first make sure the dict is sorted. if u want to get the key with highest value. then search it in second dict

r={'aday': 3, 'day': 3, 'ahaha': 1, 'donat': 1, 'kakaw': 1}
w={'ahaha': 5, 'donat': 5, 'kakaw': 5, 'aday': 4, 'day': 3}

r=({k: v for k, v in reversed(sorted(r.items(), key=lambda item: item[1]))})
print("sorted r: ", r) 

h = list(r)[0]
print("key with highest value: ", h)

g=[]
if h in w:
    g.append(w[h])
print(g)

CodePudding user response:

I'm not sure what you want to do. but according to your code it seems like you want to get the items in both dicts which are same by key and value.

this can be a simpler code for this:

r={'aday': 3, 'day': 3, 'ahaha': 1, 'donat': 1, 'kakaw': 1}
w={'ahaha': 5, 'donat': 5, 'kakaw': 5, 'aday': 4, 'day': 3}

g =[]
for key in r:
    # if both key and value are same in both dicts
    if key in w and r[key] == w[key]:
        g.append(r[key])
        g.append(w[key]) 
        
print(g)

CodePudding user response:

In the code you submitted:

  • ke is the key in r, so it will take the values aday, day, ahaha, donat, kakaw.

  • va is the value in r, it will take the values 3, 3, 1, 1, 1.

Similarly, in the w dict, da is the key and ty is the value.

So to take the key of the second array, you should change the append in your code for:

g.append(da)
  • Related