简体   繁体   中英

extract key-value pairs from a python dictionary, according to the value of a specific key

I have a list of dictionary or a dictionary of list, d1 and d2 as below.

d1 = [{'A':1, 'B':2, 'score':1},{'A':11, 'B':22, 'score':2},{'A':111, 'B':2222, 'score':3}]
d2 = {'A':[1,11,111], 'B':[2,22,222], 'score':[1,2,3]}

I need to 'filter' the dictionary by value of a key. For example, I need the value of 'A' and 'B' , where score is highest. What I want is:

{'A':111, 'B':2222}

One way I can do is to convert the dictionary list to pandas dataframe, filter rows and convert back to dictionary. But that is really inefficient....

Thanks a lot for advice in advance.

How about something like this?

d1 = [{'A':1, 'B':2, 'score':1}, {'A':11, 'B':22, 'score':2},{'A':111, 'B':2222, 'score':3}]
d2 = {'A':[1,11,111], 'B':[2,22,222], 'score':[1,2,3]}

a = []
for i in d1:
    a.append(i['score'])

b = max(a)

for i in d1:
    if i['score'] == b:
        c = i
        del c['score']

print(c)
 (xenial)vash@localhost:~/python/stack_overflow$ python3.7 sent_find.py {'A': 111, 'B': 2222}

将 d1 转换为 d2 样式,然后

idx=d2['score'].index(max(d2['score']))

_new = {'A':d2['A'][idx], 'B': d2['B'][idx]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM