Python printing single key/value pairs from a dict
本问题已经有最佳答案,请猛点这里访问。
假设我有下面的代码来做口述:
1 2 3 4 5 6 7 8 9 10 11 12 | x = 0 myHash = {} name = ["Max","Fred","Alice","Bobby"] while x <= 3: myHash[name[x]] = x x += 1 l = sorted(myHash.values(), reverse=True) largestNum = l[0] # print myHash.getKeyFromValue(largestNum) |
是否可以轻松获取与我的
注意:我不想从键中获取值。我想要与之相反的。
不要只对
1 2 3 4 | from operator import itemgetter l = sorted(myHash.items(), key=itemgetter(1), reverse=True) largestKey, largestNum = l[0] |
注:如果只想得到最大值,而不是排序结果的其余部分,则可以节省一些工作,跳过完整的
1 | largestKey, largestNum = max(myHash.items(), key=itemgetter(1)) |
号
对于反转
1 | invert_dict = {v: k for k, v in orig_dict.items()} |
如果值不是唯一的,并且希望通过一次查找查找与单个值对应的所有键,则可以反转为多个dict:
1 2 3 4 5 6 7 | from collections import defaultdict invert_dict = defaultdict(set) for k, v in orig_dict.items(): invert_dict[v].add(k) # Optionally convert back to regular dict to avoid lookup auto-vivification in the future: # invert_dict = dict(invert_dict) |
。