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

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}

猜你喜欢

转载自www.cnblogs.com/cutomorrowsmile/p/13398024.html
今日推荐