复制' N'从一个python字典到另一个python字典的键值对

时间:2014-11-15 17:15:50

标签: python dictionary

  

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

这就是我想要实现的目标。

2 个答案:

答案 0 :(得分:2)

您可以使用popitem从字典中提取任意项目:

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'}

<强> NB

尽管上述输出显示,但无法保证以任何特定顺序提取项目。

答案 1 :(得分:0)

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]