Python 复制词典与添加元素重建词典
在python中,我需要从现有词典重建词典。字典元素的数量大约为5个。我可以用这五个元素制作一本新词典,也可以复制现有词典 在复制和制作新的方法之间,哪种方法更快 (我需要把这个放到for循环中,这样在最后可能会有很大的不同。) 示例代码:Python 复制词典与添加元素重建词典,python,performance,dictionary,Python,Performance,Dictionary,在python中,我需要从现有词典重建词典。字典元素的数量大约为5个。我可以用这五个元素制作一本新词典,也可以复制现有词典 在复制和制作新的方法之间,哪种方法更快 (我需要把这个放到for循环中,这样在最后可能会有很大的不同。) 示例代码: orig = {'pid': 12345, 'name': 'steven king', 'country': 'usa', 'sex': 'M', 'company': 'MS'} for _ in range(5000): copy1 = o
orig = {'pid': 12345, 'name': 'steven king', 'country': 'usa', 'sex': 'M', 'company': 'MS'}
for _ in range(5000):
copy1 = orig.copy()
newone = {}
newone['pid'] = 12345
newone['name'] = 'steven king',
newone['country']= 'usa'
newone['sex'] = 'M'
newone['company] = 'MS'
还有一种方法可以使用
参数解包
newone = {**orig}
您还可以在该行中添加新变量:
newone = {**orig, 'newval': 'test'}
但是从我的简单测试来看,copy
方法似乎是最快的:
from timeit import timeit
orig = {'pid': 12345, 'name': 'steven king', 'country': 'usa', 'sex': 'M', 'company': 'MS'}
def f1():
newone = orig.copy()
newone['newval'] = 'test'
def f2():
newone = {}
newone['pid'] = 12345
newone['name'] = 'steven king',
newone['country']= 'usa'
newone['sex'] = 'M'
newone['company'] = 'MS'
newone['newval'] = 'test'
def f3():
newone = {**orig, 'newval': 'test'}
print(timeit(f1))
print(timeit(f2))
print(timeit(f3))
结果:
1.4525865920004435
1.858240751986159
1.4954008519998752
请尝试此处:您的预期输出是什么?您是否只是试图复制或提取每个dict中的某些元素?请看。@Jab我需要在for循环中添加新元素到新字典中。保存所有的字典。你试过自己计时和看吗?