python将字典转化为列表的六种方法
时间: 2023-06-26 11:10:13 浏览: 331
以下是Python中将字典转换为列表的六种方法:
1. 使用dict.items()
```
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = list(my_dict.items())
print(my_list)
# Output: [('a', 1), ('b', 2), ('c', 3)]
```
2. 使用dict.keys()和dict.values()
```
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(my_dict.keys())
values_list = list(my_dict.values())
print(keys_list)
print(values_list)
# Output: ['a', 'b', 'c']
# Output: [1, 2, 3]
```
3. 使用列表推导式
```
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = [(k, v) for k, v in my_dict.items()]
print(my_list)
# Output: [('a', 1), ('b', 2), ('c', 3)]
```
4. 使用zip()函数
```
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = list(zip(my_dict.keys(), my_dict.values()))
print(my_list)
# Output: [('a', 1), ('b', 2), ('c', 3)]
```
5. 使用pandas库
```
import pandas as pd
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_df = pd.DataFrame(list(my_dict.items()), columns=['key', 'value'])
my_list = my_df.values.tolist()
print(my_list)
# Output: [['a', 1], ['b', 2], ['c', 3]]
```
6. 使用pandas库的to_records()函数
```
import pandas as pd
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['value'])
my_df.index.name = 'key'
my_list = my_df.to_records().tolist()
print(my_list)
# Output: [('a', 1), ('b', 2), ('c', 3)]
```
阅读全文