Python:dict理解:使用旧字典ID中的新值制作新字典 [英] Python: dict comprehensions: making a new dictionary with new values from old dictionary ids

查看:73
本文介绍了Python:dict理解:使用旧字典ID中的新值制作新字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的字典.我正在尝试使用旧字典中的id和旧字典中的值的长度作为新字典的值来创建新字典.我在堆栈溢出上花了一个小时,试图找到我的答案,但对我没有任何帮助.我已经在PEP 274 python页面上尝试过一些示例,此处的主题为 https: //www.python.org/dev/peps/pep-0274/.

I have a simple dictionary. I am trying to create a new dictionary with the ids from the old dictionary and the lengths of the values from the old dictionary as values for the new dictionary. I have spent an hour on stack overflow trying find my answer but nothing has worked for me. I've tried some of the examples on the PEP 274 python page on the subject here https://www.python.org/dev/peps/pep-0274/ as well.

这是我正在尝试的(python 2.7):

Here is what I am trying (python 2.7):

for k, v in old_dict.iteritems():
    new_dict = { k : len(v) for k in old_dict.keys() for v in old_dict.values()} 

这给了我一本不错的新字典,带有旧字典的ID,但是所有ID的value字段都是相同的.例如:

this gives me a nice new dictionary with the old dictionary's ids, but the value field is the same across all ids. For example:

old_dict = {'a':'andkfndknskfn', 'b':'nadfnn', 'c':'fn'}

使用上面的代码,我得到:

with my code above I get:

new_dict = {'a':13, 'b':13, 'c':13}

我想要的是:

new_dict = {'a':13, 'b':6, 'c': 2}

我请求您对我表示同情:)我确实花了很长时间尝试自己找到答案,但我根本没有成功.在此先感谢您帮助我找到一个确定的答案.

I beg you take pity on me :) I really did try for quite a while to find the answer myself but I am simply not successful. Thank you in advance for helping me find what I'm sure is a simple answer.

推荐答案

您正在混合使用字典理解和for循环,它们或多或少都具有相同的作用.只需这样做:

You're mixing the dictionary comprehension and the for loop, which both do more or less the same thing. Just do this:

new_dict = { k: len(v) for k, v in old_dict.iteritems()}

这篇关于Python:dict理解:使用旧字典ID中的新值制作新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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