python-dict(字典)

字典(dict)是键值对的无序集合。字典中的每个元素包含用冒号隔开的“键”和“值”两部分,表示一种映射关系,也称之为关联数组。字典中的“键”可以是python中任意不可变数据,如整数、元祖、和字符串等,而且“键”不可以重复,“值”可以重复。
 

创建字典
使用{}创建
book_author = {
    '三国演义': '罗贯中',
    '水浒传': '施耐庵',
    '西游记': '吴承恩',
    '红楼梦': '曹雪芹'
}
print(book_author)
# {'三国演义': '罗贯中', '水浒传': '施耐庵', '西游记': '吴承恩', '红楼梦': '曹雪芹'}
使用构造函数dict()创建
# 1
book_author= (('三国演义', '罗贯中'), ('水浒传', '施耐庵'), ('西游记', '吴承恩'), ('红楼梦', '曹雪芹'))
book_author= dict(boobook_author)
print(book_author)
# {'三国演义': '罗贯中', '水浒传': '施耐庵', '西游记': '吴承恩', '红楼梦': '曹雪芹'}

# 2
# book= ('三国演义', '水浒传', '西游记', '红楼梦')
# author= ['罗贯中', '施耐庵', '吴承恩', '曹雪芹']
dict(zip(book, author))
print(book_author)
# {'三国演义': '罗贯中', '水浒传': '施耐庵', '西游记': '吴承恩', '红楼梦': '曹雪芹'}
使用类方法fromkeys()创建
book = ['三国演义', '水浒传', '西游记', '红楼梦']
# book_author= dict.fromkeys(book_list, '作者')
print(book_author)
# {'三国演义': '作者', '水浒传': '作者', '西游记': '作者', '红楼梦': '作者'}
使用字典推导式(dict comprehension)创建
book = ('三国演义', '水浒传', '西游记', '红楼梦')
author= ['罗贯中', '施耐庵', '吴承恩', '曹雪芹']
book_author = {b: w for b, w in zip(book, write)}
print(book_author)
# {'三国演义': '罗贯中', '水浒传': '施耐庵', '西游记': '吴承恩', '红楼梦': '曹雪芹'}

 
 
参考
Python字典(dict)创建
Python 中3种创建字典数据的方法
5. Data Structures
Mapping Types — dict
PEP 274 – Dict Comprehensions

posted @ 2022-04-04 11:34  Soldier&Justice  阅读(142)  评论(0编辑  收藏  举报