用python计数字典里其中一个键嵌套的键出现次数
时间: 2023-05-31 19:06:59 浏览: 91
Python数据分析中Groupby用法之通过字典或Series进行分组的实例
假设有如下字典:
```
my_dict = {
"key1": {
"nested_key1": "value1",
"nested_key2": "value2"
},
"key2": {
"nested_key1": "value3",
"nested_key2": "value4"
},
"key3": {
"nested_key1": "value5",
"nested_key2": "value6",
"nested_key3": {
"nested_nested_key1": "value7"
}
}
}
```
现在要计算嵌套在`"nested_key1"`键下面的值出现的次数。可以使用以下代码:
```
count_dict = {}
for key, value in my_dict.items():
if "nested_key1" in value:
nested_value = value["nested_key1"]
if nested_value in count_dict:
count_dict[nested_value] += 1
else:
count_dict[nested_value] = 1
print(count_dict)
```
输出结果为:
```
{'value1': 1, 'value3': 1, 'value5': 1}
```
其中,`count_dict`记录了嵌套在`"nested_key1"`键下面的值出现的次数。
阅读全文