以编程方式生成要放入python字典的键和值 [英] programmatically generate key and values to put in python dictionary

查看:54
本文介绍了以编程方式生成要放入python字典的键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成大量键值对,以使用for循环放入我的字典中.例如,字典如下所示:

I want to generate a large number of key value pairs to put in my dictionary using a for loop. For example, the dictionary looks like this:

my_dict = dict()
my_dict["r0"] = "tag 0"
my_dict["r1"] = "tag 1"
my_dict["r2"] = "tag 2"
...

请注意,键和值都遵循一种模式,即数字增加1.现在我不能执行1M次,而是希望使用自动方式来初始化字典.

Note that both the key and value follows a pattern, i.e., the number increase by 1. Now I cannot do this 1M times and would prefer an automatic way to initialize my dictionary.

推荐答案

最有效的方法 可能是对dict的理解:

The most efficient way to do this is probably with a dict comprehension:

mydict={'r%s'%n : 'tag %s'%n for n in range(10)}

等同于:

mydict=dict()
for n in range(10):
    mydict.update({'r%s'%n:'tag %s'%n})

...但是效率更高.只需根据需要更改 range(10).

... but more efficient. Just change range(10) as necessary.

您也可以在字典中使用 .format()格式,而不是百分比(类似C的)格式:

You could also use .format() formatting instead of percent (C-like) formatting in the dict:

mydict={'r{}'.format(n) : 'tag {}'.format(n) for n in range(10)}


如果您使用的是Python2,则将所有 range()函数替换为 xrange()函数

这篇关于以编程方式生成要放入python字典的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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