Python编程整理:创建字典的几种方法

时间:2020-07-29 17:41:01   收藏:0   阅读:55

1. dict函数

dict函数时python内置创建字典的函数,用法如下:

person1 = [Tom, 10]
person2 = [Lily, 11]
dict1 = dict([person1, person2])
print(dict1)

# {‘Tom‘: ‘10‘, ‘Lily‘: ‘11‘}

 

还有另一种直接使用赋值的用法:

dict1 = dict(tom = 10, lily = 11)
print(dict1)

# {‘tom‘: 10, ‘lily‘: 11}

 

2. 使用fromkeys函数:

fromkeys函数在确定键的情况下可以帮助快速创建初始字典

比如:

keys = [name, age, gender, contact.info]
dict1 = {}.fromkeys(keys, None)
print(dict1)

# {‘name‘: None, ‘age‘: None, ‘gender‘: None, ‘contact.info‘: None}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!