输出结果同样为:
{'name': 'John', 'age': 30, 'city': 'New York'}
如果可迭代对象是一个包含可哈希的键值对元组的集合,处理方式与列表类似 。
my_set = {('name', 'John'), ('age', 30), ('city', 'New York')}my_dict = dict(my_set)print(my_dict)
输出结果同样为:
{'name': 'John', 'age': 30, 'city': 'New York'}
需要注意的是,在转换过程中,dict()函数会自动忽略重复的键值对 。只有最后一个具有相同键的键值对将保留在生成的字典中 。
当你需要将可迭代对象转换为字典时,可以使用dict()函数来实现这个转换 。这在处理需要使用字典数据结构的数据时非常有用 。
需要熟悉的代码
dict1 = {'<': 'less than','==': 'equal'}print('Here is the original dict:')for x in sorted(dict1):print(f"Operator {x} means {dict1[x]}.")print("")dict1['>'] = 'greater than'print("The dict was changed to:")for x in sorted(dict1):print(f'Operator {x} means {dict1[x]}.')
dict1 = {'name': 'Niuniu','Student ID': 1}dict2 = {'name': 'Niumei','Student ID': 2}dict3 = {'name': 'Niu Ke Le','Student ID': 3}list1 = []list1.append(dict1)list1.append(dict2)list1.append(dict3)for i in list1:print(f"{i['name']}'s student id is {i['Student ID']}.")
【python入门速通基础】dict1 ={'Beijing': {'Capital': 'China'},'Moscow': {'Capital': 'Russia'},'Paris': {'Capital': 'France'}}for i in sorted(dict1):print(f"{i} is the capital of {dict1[i]['Capital']}!")
- 透传 esp8266,使用python分别建立客户端连接并实现数据互传
- python爬取微博数据词云_Python爬取微博数据生成词云图片
- Python创始人亲自推荐,238万人在学,作者:学不会我退出编程界
- ?一个超有意思的 Python 综合能力测试网站
- 09-06 周二 Python之KNN算法的实现
- 使用Python免费批量查询企业司法信息
- python 三体 模拟_三体究竟有多可怕?用Python建模来深度了解
- python+Layaair引擎学做html5棋牌游戏开发
- 评论时间、用户ID、评论内容 用python爬取影评及影片信息
- 推荐|机器学习入门方法和资料合集