python入门速通基础( 九 )


输出结果同样为:
{'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']}!")