繁体   English   中英

将“ N”个键值对从一个python字典复制到另一个

[英]Copy 'N' key value pairs from one python dictionary to another

def func(x):

 a = {} #empty dict b = somefunc() # This returns a dictionary with key value pairs for i in range(0,x): # copy any one key value pair from b to a # delete it from b 

这是我想要实现的。

您可以使用popitem从dict中提取任意项:

x = 5
a = {}
b = dict(enumerate('ABCDEFGHIJKLM'))

while x > 0:
    try:
        key, value = b.popitem()
    except KeyError:
        break
    else:
        a[key] = value
        x -= 1

print(a)
print(b)

输出:

{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
{5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J'}

注意

尽管以上输出表明,不能保证将以任何特定顺序提取项目。

python 2x

import random
a = {} #empty dict
b = somefunc() # This returns a dictionary with key value pairs
b_key = b.viewkeys()
for x in range(0,x)
    element = random.choice(b_key)
    a[element] = b[element]
    del b[element]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM