Write a function named dl_to_ld to split a given dictionary of lists into lists of dictionaries. For example, if d = {'Macro': [88, 89, 62, 95], 'Micro': [77, 78, 84, 80]}, dl_to_ld(d) should return [{'Macro': 88, 'Micro': 77}, {'Macro': 89, 'Micro': 78}, {'Macro': 62, 'Micro': 84}, {'Macro': 95, 'Micro': 80}]
时间: 2023-08-06 12:15:10 浏览: 58
Sure, here's a Python function named `dl_to_ld` that can split a given dictionary of lists into lists of dictionaries:
```python
def dl_to_ld(d):
# Get the keys of the dictionary
keys = list(d.keys())
# Find the length of the first list in the dictionary
n = len(d[keys[0]])
# Initialize an empty list of dictionaries
ld = [{} for i in range(n)]
# Iterate over the keys and values of the dictionary
for k, v in d.items():
# Iterate over the length of the list
for i in range(n):
# Add the key-value pair to the corresponding dictionary
ld[i][k] = v[i]
return ld
```
For example, if we have the dictionary `d = {'Macro': [88, 89, 62, 95], 'Micro': [77, 78, 84, 80]}`, calling `dl_to_ld(d)` will return the list of dictionaries `[{'Macro': 88, 'Micro': 77}, {'Macro': 89, 'Micro': 78}, {'Macro': 62, 'Micro': 84}, {'Macro': 95, 'Micro': 80}]`.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)