dic.fromkeys()


dict.fromkeys(seq[, value]) 该方法返回一个新字典。
  • seq -- 字典键值列表。
  • value -- 可选参数, 设置键序列(seq)对应的值,默认为 None。


a = [1, 2, 4, 2, 4, 5, 6, 5, 7, 8, 9, 0]
b = {}
b = b.fromkeys(a)
c = list(b.keys())

输出:
[1, 2, 4, 5, 6, 7, 8, 9, 0]

 

fromkeys的用法:

用于创建并返回一个新的字典。两个参数:第一个是字典的键,第二个(可选)是传入键的值,默认为None。

例如:

dict1 = dict.fromkeys([1,2,3])
print(dict1)
dict1 = dict.fromkeys((1,2,3))
print(dict1)
这两种方式是一样的,结果为

 

再例如:

dict2 = dict.fromkeys([1,2,3],'test')
print(dict2)
结果为:

 

这里要注意一点,再例如:

dict3 = dict.fromkeys([1,2,3],['one','two','three'])
print(dict3)
这段代码并不能把one,two,three分别赋值给123,而是吧['one', 'two', 'three']当作一个值赋给了3个键。

结果为:

原文链接:https://blog.csdn.net/likunkun__/article/details/81122375

posted on 2022-09-21 10:21  lmqljt  阅读(140)  评论(0编辑  收藏  举报

导航