python 打印字典
时间: 2023-06-29 14:09:32 浏览: 50
可以使用 Python 的 `print()` 函数来打印字典。以下是一个简单的示例:
```python
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict)
```
输出:
```
{'name': 'Alice', 'age': 25, 'city': 'New York'}
```
你也可以使用循环遍历字典中的键和值,然后将它们打印出来:
```python
for key, value in my_dict.items():
print(key, ":", value)
```
输出:
```
name : Alice
age : 25
city : New York
```
相关问题
python打印字典
以下是Python打印字典的几种方法:
1. 使用print()函数打印整个字典
```python
dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(dict) # 输出:{'name': 'John', 'age': 25, 'city': 'New York'}
```
2. 使用for循环遍历字典的键和值,并打印出来
```python
dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for key, value in dict.items():
print(key + ": " + str(value))
# 输出:
# name: John
# age: 25
# city: New York
```
3. 使用for循环遍历字典的键,并打印出键和对应的值
```python
dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for key in dict.keys():
print(key)
print(dict[key])
# 输出:
# name
# John
# age
# 25
# city
# New York
```
python 打印字典换行
可以通过循环打印每个键值对,并在每个键值对后面加上换行符"\n"来实现字典的换行打印,示例代码如下:
```python
my_dict = {"name": "John", "age": 25, "city": "New York"}
for key, value in my_dict.items():
print(key, ":", value)
print("\n")
```
输出结果:
```
name : John
age : 25
city : New York
```