Python 字典Dict中fromkeys函数的运用

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

两种用法:
第一种:不指定值:

x = ('key1', 'key2', 'key3')
 
thisdict = dict.fromkeys(x)
 
print(thisdict)


结果为:

{'key1': None, 'key2': None, 'key3': None}
第二种:指定值:

seq = ('name', 'age', 'sex')
 
dict = dict.fromkeys(seq, 10)
print ("新的字典为 : %s" %  str(dict))


结果为:

新的字典为 : {'age': 10, 'name': 10, 'sex': 10}
 

注意 :
    该方法也可以用于对列表进行去重:
    案例如:

a = [1, 2, 4, 2, 4, 5, 6, 5, 7, 8, 9, 0]
b = {}
b = b.fromkeys(a)
c = list(b.keys())
发布了289 篇原创文章 · 获赞 163 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/Suyebiubiu/article/details/103108873