我有一本这样的字典
x={6:{"Apple","Banana","Tomato"},9:{"Cake"},11:{"Pineapple","Apple"}}
我想添加一个丢失的数字作为键,空字符串作为值,如下所示
x={1:"",2:"",3:"",4:"",5:"",6:{"Apple","Banana","Tomato"},7:"",8:"",9:{"Cake"},10:"",11:{"Pineapple","Apple"}}
我该怎么办?谢谢你的进阶
发布于 2021-12-03 15:54:28
建立一个具有理解力的新词条:
>>> x={6:{"Apple","Banana","Tomato"},9:{"Cake"},11:{"Pineapple","Apple"}}
>>> x = {k: x.get(k, "") for k in range(1, max(x)+1)}
>>> x
{1: '', 2: '', 3: '', 4: '', 5: '', 6: {'Banana', 'Tomato', 'Apple'}, 7: '', 8: '', 9: {'Cake'}, 10: '', 11: {'Apple', 'Pineapple'}}
根据您的用例,您可能还发现defaultdict
很有用,例如:
>>> from collections import defaultdict
>>> x = defaultdict(str)
>>> x.update({6:{"Apple","Banana","Tomato"},9:{"Cake"},11:{"Pineapple","Apple"}})
>>> x[6]
{'Banana', 'Tomato', 'Apple'}
>>> x[1]
''
defaultdict
的思想是,如果没有设置其他值,您尝试访问的任何键都将提供默认值(在本例中为str()
) --没有必要提前填写“缺失”值,因为字典将根据需要提供这些值。如果您需要对整个字典进行迭代并包含这些空值,那么这种方法就无法工作。
发布于 2021-12-03 15:59:40
您可以使用dict.fromkeys
构建字典,然后用x
更新该字典。
out = {**dict.fromkeys(range(1, max(x)+1), ""), **x}
输出:
{1: '', 2: '', 3: '', 4: '', 5: '', 6: {'Tomato', 'Apple', 'Banana'},
7: '', 8: '', 9: {'Cake'}, 10: '', 11: {'Apple', 'Pineapple'}}
dict.fromkeys(iterable, value=None)
文档字符串:
创建一个新字典,其中包含来自
iterable
的键并将值设置为value
。
dict.fromkeys(range(1, max(x)+1), "")
# {1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: '', 10: '', 11: ''}
我们可以使用{**x, **y}
合并两个数据集。退房:Merge two dictionaries in python
发布于 2021-12-03 15:56:21
循环从0到11的数字。如果字典中找不到一个数字,就添加它。
for n in range(12):
if n not in x:
x[n] = ""
https://stackoverflow.com/questions/70217093
复制相似问题