将dict的元组键转换为新的命令 [英] convert tuple keys of dict into a new dict

查看:136
本文介绍了将dict的元组键转换为新的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 dict ,如下所示:

{
    ('America', 25, 'm', 'IT'): 10000,
    ('America', 22, 'm', 'IT'): 8999,
    ('Japan',   24, 'f', 'IT'): 9999,
    ('Japan',   23, 'f', 'IT'): 9000
}

现在,我想用key ('America','m','IT')获得所有结果,在这个例子中。在上面,这将是:

Now, I want to get all result with key ('America', 'm', 'IT'), in this example. In the above, that would be:

{25: 10000, 22: 8999}

我目前的解决方案如下:

My current solution is below:

res = dict()
for key, cnt in stats.items():
    country, age, sex, job = key
    try:
        res[(country, sex, job)][age] = cnt
    except KeyError as e:
        res[(country, sex, job)] = {}
        res[(country, sex, job)][age] = cnt

print res['America', 'm', 'IT']

我有更好的办法吗?因为这段代码似乎并不简单。

Do I have better ways to do is? since this code does not seem that simple.

推荐答案

您可以使用字母理解来执行此操作:

You can use a dict comprehension to do this:

>>> data = {
...     ('America', 25, 'm', 'IT'): 10000,
...     ('America', 22, 'm', 'IT'): 8999,
...     ('Japan',   24, 'f', 'IT'): 9999,
...     ('Japan',   23, 'f', 'IT'): 9000
... }
>>> {x: value for (w, x, y, z), value in data.items() if w == "America" and y == "m" and z == "IT"}
{25: 10000, 22: 8999}

这篇关于将dict的元组键转换为新的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆