python 多层字典读取
时间: 2024-01-19 18:18:02 浏览: 167
python requests post多层字典的方法
以下是Python多层字典读取的方法:
1. 使用多个方括号进行索引
```python
dict1 = {'a': {'b': {'c': 1}}}
value = dict1['a']['b']['c']
print(value) # 输出:1
```
2. 使用get()方法进行索引
```python
dict1 = {'a': {'b': {'c': 1}}}
value = dict1.get('a').get('b').get('c')
print(value) # 输出:1
```
3. 使用reduce()函数进行索引
```python
from functools import reduce
dict1 = {'a': {'b': {'c': 1}}}
keys = ['a', 'b', 'c']
value = reduce(lambda d, key: d.get(key), keys, dict1)
print(value) # 输出:1
```
4. 使用try-except语句进行索引
```python
dict1 = {'a': {'b': {'c': 1}}}
try:
value = dict1['a']['b']['c']
print(value) # 输出:1
except KeyError:
print("Key not found")
```
阅读全文