【发布时间】:2017-07-09 17:31:05
【问题描述】:
我需要制作一个只包含键的字典。
我不能使用d.append(),因为它不是一个列表,也不是setdefault,因为它需要两个参数:一个键和一个值。
它应该如下工作:
d = {}
添加“a”:
d = {"a"}
添加“b”:
d = {"a", "b")
添加“c” ...
#Final result is
d = {"a", "b", "c"}
我需要什么代码才能得到这个结果? 还是另一种解决方案?比如列一个清单。
l = ["a", "b", "c"] # and transform it into a dictionnary: d = {"a", "b", "c"} ?
【问题讨论】:
-
d = {"a", "b", "c"}这不是字典 只是set -
如果你从
d = set()开始而不是d = {},它会起作用的。 -
你需要的是
set而不是字典 -
dict.fromkeys('abc')会给你{'a': None, 'c': None, 'b': None},但听起来你想要的是set。
标签: python dictionary append key