标签: fromkeys

如何使用dict.fromkeys为每个键创建唯一值?

首先,我是Python的新手,所以如果我忽略了某些内容,我会道歉,但我想使用dict.fromkeys(或类似的东西)来创建列表字典,其中的键在另一个列表中提供.我正在执行一些计时测试,我希望键是输入变量,列表包含运行的时间:

def benchmark(input):
    ...
    return time_taken

runs = 10
inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55)
results = dict.fromkeys(inputs, [])

for run in range(0, runs):
    for i in inputs:
        results[i].append(benchmark(i))
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是字典中的所有键似乎共享相同的列表,每次运行只是附加到它.有没有办法为每个密钥生成一个唯一的空列表fromkeys?如果没有,是否有其他方法可以手动生成结果字典?

python dictionary fromkeys

11
推荐指数
2
解决办法
5574
查看次数

python dict.fromkeys()返回空

我写了以下函数.它不应该返回一个空字典.代码在没有功能的命令行上工作.但是我看不出这个功能有什么问题,所以我必须诉诸你的集体智慧.

def enter_users_into_dict(userlist):
    newusr = {}
    newusr.fromkeys(userlist, 0)
    return newusr

ul = ['john', 'mabel']
nd = enter_users_into_dict(ul)
print nd
Run Code Online (Sandbox Code Playgroud)

它返回一个空的dict {},我希望{'john':0,'mabel':0}.

它可能非常简单,但我没有看到解决方案.

python dictionary fromkeys

2
推荐指数
1
解决办法
1714
查看次数

标签 统计

dictionary ×2

fromkeys ×2

python ×2