重命名字典键仅在特定值

发布于 2025-02-11 02:58:23 字数 456 浏览 3 评论 0原文

我在python中有一个名为“电影”的词典列表,每个词典都显示了电影的相同键: (即“标题”,由'发布日期等制作的)。 不幸的是,我发现列表中的某些词典中有一个名为“发布日期”的密钥,而不是'发布日期'。

因此,我的任务是更改其名称,以使所有字典都具有相同的键“发行日期” 。 我尝试了一下:

for dic in Movies:
          for k,v in dic.items():
                if dic[k] == 'Release date':
                           dic[k]='Release dates'

不幸的是,当我尝试以下检查时:

print([m.keys() for m in Movies])

它仍然返回旧键而没有任何更改

,我不知道我在哪里错了

I have a list of dictionaries in Python called 'Movies' where every dictionary shows the same keys for a movie:
(i.e "Title","Produced by,'Release dates' etc.).
Unfortunatley, I found out that some of these dictionaries in the list have a key called 'Release date" instead of 'Release dates'.

So my task is to change their name in order to have all dictionary with the same key "Release dates".
I tried this:

for dic in Movies:
          for k,v in dic.items():
                if dic[k] == 'Release date':
                           dic[k]='Release dates'

Unfortunately, when I try the following check:

print([m.keys() for m in Movies])

it still returns the old keys without any change

I don't know where I'm wrong

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

睡美人的小仙女 2025-02-18 02:58:23

好的,也许我找到了解决方案。问题是由于在某些词典中找不到可以替代的关键名称,因此我必须通过检查。在这里,解决方法:

for dic in Movies:
    if 'Release date' in dic:
        dic['Release dates']=dic.pop('Release date')
print(Movies)

Ok, maybe I find the solution. The Problem was due to the fact that in some dictionaries it couldn't find the key name to substitute so I have to pass a check. Here the workaround:

for dic in Movies:
    if 'Release date' in dic:
        dic['Release dates']=dic.pop('Release date')
print(Movies)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文