【问题标题】:Modifing keys of a dict while iterating迭代时修改字典的键
【发布时间】:2021-07-01 03:27:51
【问题描述】:

所以我试图在迭代它们的同时修改 dict 的键,这似乎是 python 并不真正希望你做的事情。因此,我想问,我怎样才能绕过 python 的限制?这是我的第一个代码,问题是 dict.items() 不允许您修改 dict 的键,而是让您查看 dict。

d = {k: dict(zip(v['EST'], v['value'])) for k, v in df1.groupby('variable')}

order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
Days = [key for key in d]
Days.sort(key=order.index)

templist = []

Better version
for day in Days:
     for key, value in d[day].items():
        if 'EST' not in key :
            key = ''.join(('Time ', key))
            if 'Time' in key:               templist = key.rsplit(":", 1)
                 key = ''.join(templist)
                 print(f"Yes this is the {day}, {key} EST and the {value}")

由于这并没有修改字典的原始值,我尝试在迭代时修改它们,但也得到了一个 RuntimeError: dictionary changed size during iteration

    for j in d[i]:
        if 'EST' not in j :
            d[j] = ''.join(('Time ', j))

基本上,我想修改 dict 的键,但我不被允许,那我该怎么办?谢谢。

【问题讨论】:

  • 更改dict 中的键相当于删除现有条目并添加具有相同值的新条目。取决于你想做什么,这可能很繁琐。不要更改现有dict 的键,而是循环通过.items() 并构建一个新的。
  • @BoarGules 问题是因为我修改了密钥,在修改密钥后再次循环 .items() 只会给我旧值。除了我能够在修改值时以某种方式构建一个新的字典。

标签: python loops dictionary iteration


【解决方案1】:

只需用元组包装 .items() 调用即可。

类似的,

for day in Days:
     for key, value in tuple(d[day].items()):
        if 'EST' not in key :
            key = ''.join(('Time ', key))
            if 'Time' in key:               templist = key.rsplit(":", 1)
                 key = ''.join(templist)
                 print(f"Yes this is the {day}, {key} EST and the {value}")

更新#1: 好吧,我的意思是,

abc = dict()

for key, value in tuple(abc.items()):
    # Modify dict somehow
    abc[somekey] = somevalue # This would work

我无法完全理解您的要求。但我确实理解你的问题,我认为这会解决它。

【讨论】:

  • 即使退出循环,我也看不出这将如何让我更改密钥。
【解决方案2】:

所以这个问题的答案是 python 不允许你修改你正在迭代的字典,因此,需要创建字典的副本并在使用副本的索引更改原始字典时迭代副本.请记住,有两种类型的复制,深的和浅的。根据您的需要使用正确的。

    for key in dictionary_from_numpy[day].copy():
        if 'EST' not in key:
            copy_of_dictionary_from_numpy[day][x] = copy_of_dictionary_from_numpy[day].pop(key)

第二件事是您必须弹出要从字典中删除的键。这会将你的钥匙推到字典的后面,所以要小心这一点。这个例子比较清楚,因为里面有实际值。

new['Friday']['rr1'] = d['Friday'].pop('1:00: AM')

【讨论】:

    猜你喜欢
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2023-04-06
    • 2021-03-30
    • 2019-06-07
    • 2011-10-14
    • 1970-01-01
    相关资源
    最近更新 更多