简体   繁体   English

正确更新动态python字典的正确方法

[英]Correct way to update a python dict dynamically

I have a python dict containing data about a table. 我有一个包含有关表数据的python字典。

table_dict = {'0': {'column_metadata': '...',
                    'cells':[[cell1_url],[cell2_url]]
                   },
              '1': {'column_metadata': '...',
                    'cells':[[cell1_url],[cell2_url]]
                   }
             }

Here keys are column position ie 0 means first column, 1 is second so on each column has a inner dict with a key cells which is list of list. 这里的键是列位置,即0表示第一列,1表示第二列,因此在每一列上都有一个内部dict,其中的键单元为list列表。

I am iterating over this dict to get cell value from url and then appending it back to same list. 我正在对该指令进行迭代以从url获取单元格值,然后将其附加回相同的列表。

for key, column in table_dict:
    for cell in column['cells']:
        cell_value = get_cell_data(cell1_url)
        column['cells'].append(cell_value)

with this code I get final dict as 有了这段代码,我得到最终的决定为

table_dict = {'0': {'column_metadata': '...',
                    'cells':[[cell1_url, cell1_data],
                             [cell2_url, cell2_data]
                            ]
                   },
              '1': {'column_metadata': '...',
                    'cells':[[cell1_url, cell1_data],
                             [cell2_url, cell2_data]
                            ]

I will not delete any keys just add data to dict. 我不会删除任何键,而只是将数据添加到字典中。

Is this the correct method. 这是正确的方法吗? Iterating over dict and then append to same. 遍历字典,然后追加到字典。

Is there any better way to approach this problem ? 有没有更好的方法来解决此问题?

From your description I assume, you does not want to append something to column['cells'] but to the lists inside this list: 根据您的描述,我认为您不想将某些内容追加到column['cells']而是追加到此列表内的列表:

for column in table_dict.values():
    for cell in column['cells']:
        cell_url = cell[0]
        cell.append(get_cell_data(cell_url))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM