【问题标题】:Replace a string stored in a list of dictionaries替换存储在字典列表中的字符串
【发布时间】:2018-10-31 21:48:45
【问题描述】:

我正在 python3 中开发一个程序,需要遍历字典列表并将所有出现的特定字符“-”替换为“_”。理想情况下,我只需要替换字典键中的 '-' 实例,但我可以通过其他方式进行管理

数据格式如下:

d=[
    {
    'title': [('Agente 007, Moonraker: Operazione spazio', 'it')], 
    'sub-title': [('Missione nel cosmo per...', 'it')], 
    },{
    'title': [('Agente 007, Vivi e lascia morire', 'it')], 
    'sub-title': [('Il primo James Bond con...', 'it')]
    }
  ]

我尝试将其替换为:

d.replace('-','_')

但这给出了错误:

AttributeError: 'list' object has no attribute 'replace'

然后我想我会遍历列表和字典项以尝试替换:

 for i in range(len(dicts)):
     for x in dicts[i].items():
         dicts[i].items.replace('-','_')

这给了我

 AttributeError: 'builtin_function_or_method' object has no attribute 'replace'

所以现在我正在尝试

def t(dicts):
    for i in range(len(dicts)):
        for key in dicts[i].items():
            dicts[i].items()[key.replace('-','_')] = (dicts[i].items()).pop(key)

但是,这会产生错误:

AttributeError: 'dict_items' object has no attribute 'pop'    

有人知道怎么做吗?如果是我做错了什么,正确的处理方法是什么?

【问题讨论】:

    标签: python-3.x list dictionary


    【解决方案1】:

    首先,

    for i in range(len(dicts)):
     for x in dicts[i].items():
         dicts[i].items.replace('-','_')
    

    您收到异常是因为您尝试在函数“items”中访问“替换”方法,而不是调用函数。应该是:

    dicts[i].items().replace('-','_')
    

    其次,对我来说这是错误的方法。 既然您使用的是 python,为什么不以 pythonic 方式执行它并返回一个具有新值的新 dicts 的新列表?

    下面提供的函数采用元组列表的字典列表(这是您提供的结构)并将每个“to_change”替换为“change_to”。我根据您的要求将每个“-”更改为“_”来调用它。

    d=[
    {
    'title': [('Agente 007, Moonraker: Operazione spazio', 'it')], 
    'sub-title': [('Missione nel cosmo per...', 'it')], 
    },{
    'title': [('Agente 007, Vivi e lascia morire', 'it')], 
    'sub-title': [('Il primo James Bond con...', 'it')]
    }
      ]  
    
    def sub_string(dict_list, to_change, change_to):
        new_list = []
        for d_orig in dict_list:
            d_new = {}
            for key in d_orig.keys():
                new_key = key.replace(to_change, change_to)
                new_value = [[s.replace(to_change, change_to) for s in tup] for tup in d_orig[key]]
                d_new[new_key] = new_value
    
            new_list.append(d_new)
        return new_list
    
    sub_string(d, '-', '_')
    

    这是你的意思吗?

    【讨论】:

    • 好吧,我有点伤心。我想接受答案,因为它是 pythonic 方式,但是对于我的大型数据集,它会导致缓冲区溢出和段错误
    • 我理解您的冲突,但请这样想:假设您的数据集是您提供的 dict 大小的一百万倍(这可能是一个延伸),大约需要 11秒 来替换数据。当然还有一些优化需要做,但是对于一次性点击忘记功能来说还不错。
    猜你喜欢
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 2021-01-02
    • 2021-05-22
    • 2013-11-18
    • 1970-01-01
    • 2020-03-07
    • 2013-05-01
    相关资源
    最近更新 更多