python字典如何转换

原创
ithorizon 7个月前 (10-02) 阅读数 26 #Python

Python字典转换

Python字典是一种可变的数据结构,它可以存储多个键值对,在Python中,可以使用多种方法将字典转换为其他数据类型。

转换为字符串

要将Python字典转换为字符串,可以使用str()函数将字典转换为字符串。

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_string = str(my_dict)
print(my_string)

输出结果为:

{'name': 'John', 'age': 30, 'city': 'New York'}

转换为列表

要将Python字典转换为列表,可以使用dict.items()方法将字典转换为元组列表。

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_list = list(my_dict.items())
print(my_list)

输出结果为:

[('name', 'John'), ('age', 30), ('city', 'New York')]

转换为元组

要将Python字典转换为元组,可以使用dict.items()方法将字典转换为元组列表,然后使用元组打包技术将元组列表转换为单个元组。

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_tuple = tuple(my_dict.items())
print(my_tuple)

输出结果为:

('name', 'John', 'age', 30, 'city', 'New York')

转换为JSON字符串

要将Python字典转换为JSON字符串,可以使用json模块中的dumps()函数将字典转换为JSON字符串。

import json
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_json = json.dumps(my_dict)
print(my_json)

输出结果为:

{"name": "John", "age": 30, "city": "New York"}


热门