每个唯一嵌套字典键值的最高字典键

huangapple go评论70阅读模式
英文:

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: {
		&#39;id&#39;: &#39;B&#39;,
	}, 
	2: {
		&#39;id&#39;: &#39;B&#39;,
	}, 
	3: {
		&#39;id&#39;: &#39;A&#39;,
	}, 
	4: {
		&#39;id&#39;: &#39;B&#39;,
	}, 
	5: {
		&#39;id&#39;: &#39;A&#39;,
	}
}

results = {}

for key, value in mydict.items():
	if (value[&#39;id&#39;] not in results) or (results[value[&#39;id&#39;]] &lt; key):
		results[value[&#39;id&#39;]] = key

print(results)

Output:

{&#39;B&#39;: 4, &#39;A&#39;: 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: {&#39;id&#39;: &#39;B&#39;,
        }, 
    2: {&#39;id&#39;: &#39;B&#39;,
        }, 
    3: {&#39;id&#39;: &#39;A&#39;,
        }, 
    4: {&#39;id&#39;: &#39;B&#39;,
        }, 
    5: {&#39;id&#39;: &#39;A&#39;,
        }, 
    }

result = { d[&#39;id&#39;]:k for k,d in mydict.items() }

print(result)
           
{&#39;B&#39;: 4, &#39;A&#39;: 5}

huangapple
  • 本文由 发表于 2023年7月12日 23:27:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定