首页 > 解决方案 > 为什么字典理解显示不同的值

问题描述

我想将字典理解应用于标题以及发布日期和趋势日期的差异。

def vid(videos):
     diff_date = [(x.trending_date - x.publish_date).days for x in videos]
     dct = {x.title : (x.trending_date - x.publish_date).days for x in videos}

     print(diff_date)
     print(dct)

diff_date 的部分输出给出:

[1, 1, 2, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2361, 1, 8, 4, 2, 2, 207, 2, 1, 2, 1, 1, 2, 1, 3, 3, 2, 1, 4, 1, 4, 3, 2, 3, 4, 3, 4, 3, 2, 1, 3, 3, 1, 4, 4, 2, 4, 3, 4, 1, 4, 5, 3, 4, 3, 4, 4, 4, 4, 4, 28, 3, 4, 4, 2, 3, 3, 5, 5, 3, 4, 2, 4, 2, 5, 5, 4, 4, 4, 5, 4, 5, 5, 4, 5, 4, 4, 4, 4, 5, 4, 4, 4, 5, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 4, 4, 4, 5, 5, 6, 5, 4, 5, 4,....

部分输出dct给出:

{'WE WANT TO TALK ABOUT OUR MARRIAGE': 7, 'The Trump Presidency: Last Week Tonight with John Oliver (HBO)': 7, 'Racist Superman | Rudy Mancuso, King Bach & Lele Pons': 8, 'Nickelback Lyrics: Real or Fake?': 7, 'I Dare You: GOING BALD!?': 7, '2 Weeks with iPhone X': 7, 'Roy Moore & Jeff Sessions Cold Open - SNL': 6, '5 Ice Cream Gadgets put to the Test': 7, 'The Greatest Showman | Official Trailer 2 [HD] | 20th Century FOX': 2, 'Why the rise of the robots won’t mean the end of work': 2, "Dion Lewis' 103-Yd Kick Return TD vs. Denver! | Can't-Miss Play | NFL Wk 10 Highlights": 1,......

如您所见, 的值与dct的输出中的值不同diff_date。我期望发生的是:

{'WE WANT TO TALK ABOUT OUR MARRIAGE': 1, 'The Trump Presidency: Last Week Tonight with John Oliver (HBO)': 1, 'Racist Superman | Rudy Mancuso, King Bach & Lele Pons': 2, 'Nickelback Lyrics: Real or Fake?': 1, 'I Dare You: GOING BALD!?': 2.......

我不确定为什么它会给出不同的值。我希望价值保持不变,对吗?

*注意函数的输入是视频类的对象

标签: pythonpython-3.xdictionarylist-comprehension

解决方案


这是因为 python 字典不是按顺序组织的。我可以向您保证,它们的价值是正确的,但订单有点混乱。您可以使用此代码来解决该问题

from collections import OrderedDict 

def vid(videos):
     dct = OrderedDict() 
     diff_date = [(x.trending_date - x.publish_date).days for x in videos]
     for x in videos:
       dct[x.title] = (x.trending_date - x.publish_date).days
     print(diff_date)
     print(dct)

这是一个订单字典。它需要更多空间,但可以使事情井井有条。欲了解更多信息,请查看这里


推荐阅读