英文:
Highest dictionary keys for each unique nested dictionary key value
问题
如何选择每个唯一的id
(即B-4和A-5)的最高mydict
键?我们可以假设数字递增。
mydict = {
1: {'id': 'B'},
2: {'id': 'B'},
3: {'id': 'A'},
4: {'id': 'B'},
5: {'id': 'A'},
}
我的解决方案可能不是最有效的:
```python
for k, v in reversed(mydict.items()):
if v['id'] not in result:
result[v['id']] = k
如需进一步解释或其他帮助,请告诉我。
英文:
How to select highest mydict
keys for each unique id
(i.e. B-4 and A-5)? We can assume the numbers increment.
mydict = {
1: {'id': 'B',
},
2: {'id': 'B',
},
3: {'id': 'A',
},
4: {'id': 'B',
},
5: {'id': 'A',
},
}
My solution may not be most efficient
for k, v in reversed(mydict.items()):
if v['id'] not in result:
result[v['id']] = k
答案1
得分: 3
以下是翻译好的代码部分:
mydict = {
1: {
'id': 'B',
},
2: {
'id': 'B',
},
3: {
'id': 'A',
},
4: {
'id': 'B',
},
5: {
'id': 'A',
}
}
results = {}
for key, value in mydict.items():
if (value['id'] not in results) or (results[value['id']] < key):
results[value['id']] = key
print(results)
Output:
{'B': 4, 'A': 5}
英文:
Here's the code to do it.
mydict = {
1: {
'id': 'B',
},
2: {
'id': 'B',
},
3: {
'id': 'A',
},
4: {
'id': 'B',
},
5: {
'id': 'A',
}
}
results = {}
for key, value in mydict.items():
if (value['id'] not in results) or (results[value['id']] < key):
results[value['id']] = key
print(results)
Output:
{'B': 4, 'A': 5}
答案2
得分: 1
只需创建一个新的字典,以id作为键,顶级键作为值。鉴于顶级字典已经按升序键排序,每个id分配的最后一个值将是找到的最后一个键(即该id的最大值):
mydict = {
1: {'id': 'B'},
2: {'id': 'B'},
3: {'id': 'A'},
4: {'id': 'B'},
5: {'id': 'A'},
}
result = {'B': 4, 'A': 5}
print(result)
{'B': 4, 'A': 5}
英文:
Simply create a new dictionary with the id's as key and the top level key as value. Given that the top level dictionary is already ordered by ascending keys, the last value assigned to each id will be the last key found (i.e. the maximum for that id):
mydict = {
1: {'id': 'B',
},
2: {'id': 'B',
},
3: {'id': 'A',
},
4: {'id': 'B',
},
5: {'id': 'A',
},
}
result = { d['id']:k for k,d in mydict.items() }
print(result)
{'B': 4, 'A': 5}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论