【问题标题】:Adding values to a dictionary key in python在python中向字典键添加值
【发布时间】:2020-06-10 22:27:07
【问题描述】:

我想在某个关键字之后扫描文本并提取数据。在这种情况下,我正在扫描sql 文件。我的字典的结构是这样的(嵌套的):

my_dict = {sql_file:{'select': table_name, 'join': table_name}}

我有一个循环遍历 sql 文件,找到关键字并为目录中的每个文件提取表。但是,因为我需要在扫描 select 关键字后更新字典然后返回并更新字典以更新 join 关键字,更新结束覆盖 我的原始字典值。这是循环的工作原理。

for key, val in file_dict.items(): # I have a dictionary that has {filename:sql_script} for key,val
    for match in select.finditer(val): # regex iterator to find all matches
        if match.group(1):
            my_dict[sql_file] = {'select': match.group(1)})


for key, val in file_dict.items(): # I have a dictionary that has {filename:sql_script} for key,val
        for match in join.finditer(val): # regex iterator to find all matches
            if match.group(1):
                my_dict[sql_file] = {'join': match.group(1)})

这最终不会添加select 匹配,然后添加join 匹配,它只是覆盖select 并将其替换为join。字典没有附加方法,所以我不知道如何继续。

【问题讨论】:

  • my_dict[sql_file]['select'] = match.group(1)
  • 你不需要 append 方法,只需分配你想要的键。
  • 你能提供一个minimal reproducible example吗?

标签: python dictionary


【解决方案1】:

从您的my_dict[sql_file] 中,您会得到另一个包含{'select': table_name, 'join': table_name} 的字典。因此,您可以像访问另一本字典一样访问这本字典:

for key, val in file_dict.items():
    for match in select.finditer(val):
        if match.group(1):
            my_dict[sql_file]['select'] = match.group(1)


for key, val in file_dict.items():
        for match in join.finditer(val):
            if match.group(1):
                my_dict[sql_file]['joinn'] = 'join': match.group(1)

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    相关资源
    最近更新 更多