Python 字典数组

标签 python list dictionary

我想询问我最近遇到的一个特定问题。

我有包含项目的列表,例如

list1 = ['library','book','room','author','description','genre','publish_date','price','title']

包含键和值的字典,键是 list1 中的项目,值是其子项,例如

dictionary1 = {'room': ['book'], 'title': [], 'price': [], 'author': [], 'library': [ 'room', 'book'], 'book': ['author', 'title', 'genre', 'price', 'publish_date', 'description'], 'publish_date': [], 'genre': [], 'description': []}

基本上我想做的是遍历dictionary1中的项目,如果某个键的值也是带值的键,我想将值的值添加到键中。

例如:

'library': ['room','book']

书籍包含作者、标题、流派、价格、出版日期、描述。

我想将所有这些项目添加到库 key 中,所以它看起来像:

'library': ['room','book','author', 'title', 'genre', 'price', 'publish_date', 'description'], 'publish_date': [], 'genre': [], 'description': []] 

最佳答案

伪代码:

dictionary = ...//your input
dictionaryOut={}

list=[]

for key, value in dictionary
    dictionaryOut[key] = copy(value)

    if length(value[0]):
        list=[value[0]]

    while not empty(list):
        list.append(dictionary(list[0]))
        dictionaryOut[key].append(dictionary(list.pop(0))

只要我们谈论Python,并且附加到值实际上会更新字典中的列表,就应该这样做。

关于Python 字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16062205/

相关文章:

python - 列表列表到字典列表

python - imoporting GDAL : ImportError, 库未加载时出现问题,找不到图像

python - Google Cloud Storage 中图像的服务 URL 是否会更改?

Python:如何处理 urllib2 中服务器抛出的异常?

使用 Contains 方法检查 List<float> 中的 float 时的 C# 准确性

javascript - JavaScript 中的 Python any() 和 all() 函数等价于什么?

python - 具有 n 个断点的分段线性拟合

list - 在 Flutter/Dart 中映射多个列表?

python - 将列表写入字典

dictionary - 在 Julia 中将 Dict 转换为 DataFrame