简体   繁体   English

从元组键字典和顺序中获取值

[英]get value from tuple keys dictionary and sequential

I have a dictionary我有字典

d = {(1,100) : 0.5 , (1,150): 0.7 ,(1,190) : 0.8, (2,100) : 0.5 , (2,120): 0.7 ,(2,150) : 0.8, (3,100) : 0.5 , (3,110): 0.7 ,(4,100) : 0.5 , (4,150): 0.7 ,(4,190) : 0.8,(5,100) : 0.5 , (5,150): 0.7}
list = [4,2,1,3,5]

for (k1,k2),k3 in d.items():
 for k1 in list :
   print(k1,k2 : ,k3)

I want get the value of dictionary sequential like my list for the key 1 and for key 2 I have diferrent score and count我想得到字典顺序的值,就像我的键 1 和键 2 的列表一样,我有不同的分数和计数

(4,100) : 0.5 , (4,150): 0.7 ,(4,190) : 0.8,(2,100) : 0.5 , (2,120): 0.7 ,(2,150) : 0.8,(1,100) : 0.5 , (1,150): 0.7 ,(1,190) : 0.8,(3,100) : 0.5 , (3,110): 0.7 ,(5,100) : 0.5 , (5,150): 0.7}

You can use sorted() with the the values from the tuple as index in the list您可以将sorted()与元组中的值一起用作列表中的索引

d = dict(sorted(d.items(), key=lambda x: lst.index(x[0][0])))
print(d)

Output Output

{(4, 100): 0.5, (4, 150): 0.7, (4, 190): 0.8, (2, 100): 0.5, (2, 120): 0.7, (2, 150): 0.8, (1, 100): 0.5, (1, 150): 0.7, (1, 190): 0.8, (3, 100): 0.5, (3, 110): 0.7, (5, 100): 0.5, (5, 150): 0.7}

Try the following:尝试以下操作:

d = {(1, 100): 0.5,
     (1, 150): 0.5,
     (1, 190): 0.8,
     (2, 100): 0.5,
     (2, 120): 0.7,
     (2, 150): 0.8,
     (3, 100): 0.5,
     (3, 110): 0.7,
     (4, 100): 0.5,
     (4, 150): 0.7,
     (4, 190): 0.8,
     (5, 100): 0.5,
     (5, 150): 0.7}


lst = [4, 2, 1, 3, 5]

for key, k3 in d.items():

    print(f'({lst[key[0]-1]},{key[1]}) : ,{k3}')

Output: Output:

(4,100) : ,0.5
(4,150) : ,0.5
(4,190) : ,0.8
(2,100) : ,0.5
(2,120) : ,0.7
(2,150) : ,0.8
(1,100) : ,0.5
(1,110) : ,0.7
(3,100) : ,0.5
(3,150) : ,0.7
(3,190) : ,0.8
(5,100) : ,0.5
(5,150) : ,0.7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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