码迷,mamicode.com
首页 > 编程语言 > 详细

【Python基础】字典函数fromkeys()

时间:2019-08-24 18:45:59      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:none   返回   rom   tps   style   元组   tle   href   默认   

字典函数fromkeys()

fromkeys()的用法:

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

实例一:

  #列表
  >>> dict1 = dict.fromkeys([1,2,3])
  >>> dict1
  {1: None, 2: None, 3: None}
  #元组
  >>> dict1 = dict.fromkeys((1,2,3))
  >>> dict1
  {1: None, 2: None, 3: None}

实例二:

  #修改默认值
  >>> dict2 = dict.fromkeys([1,2,3,],‘test‘)
  >>> dict2
  {1: ‘test‘, 2: ‘test‘, 3: ‘test‘}

  >>> dict2 = dict.fromkeys([1,2,3,],10)
  >>> dict2
  {1: 10, 2: 10, 3: 10}

实例三:

  #需要注意!
  >>> dict3 = dict.fromkeys([1,2,3],[‘one‘,‘two‘,‘three‘])
  >>> dict3
  {1: [‘one‘, ‘two‘, ‘three‘], 2: [‘one‘, ‘two‘, ‘three‘], 3: [‘one‘, ‘two‘, ‘three‘]}

应用举例:

实现删除一个list里面的重复元素

1.使用set函数   --->得到的集合无序

>>> list1 = [7,8,7,8,9,10]
>>> set(list1)
{8, 9, 10, 7}

2.使用字典函数

>>> list1 = [7,8,7,8,9,10]
>>> b = dict.fromkeys(list1)
>>> b
{7: None, 8: None, 9: None, 10: None}
>>> c = list(b.keys())
>>> c
[7, 8, 9, 10]

 

【Python基础】字典函数fromkeys()

标签:none   返回   rom   tps   style   元组   tle   href   默认   

原文地址:https://www.cnblogs.com/XJT2018/p/11405410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!