如何添加dict的特定元素

时间:2017-09-10 17:34:48

标签: python dictionary python-3.6 keyerror

sleeps=[{"summaryId ": "x209bf59-59b0c5a8-585c ", 
         "validation ": "AUTO_TENTATIVE ", 
         "durationInSeconds ": 22620, 
         "startTimeInSeconds ": 1504757160, 
         "awakeDurationInSeconds ": 900, 
         "startTimeOffsetInSeconds ": -14400, 
         "deepSleepDurationInSeconds ": 8160, 
         "lightSleepDurationInSeconds ": 13560},
        {"summaryId ": "x209bf59-59b0c5a8-23a0 ", 
         "validation ": "AUTO_TENTATIVE ",
         "durationInSeconds ": 9120, 
         "startTimeInSeconds ": 1504757160,
         "awakeDurationInSeconds ": 300, 
         "startTimeOffsetInSeconds ": -14400, 
         "deepSleepDurationInSeconds ": 1680, 
         "lightSleepDurationInSeconds ": 7140}
       ]

res = sum([x["durationInSeconds"] for x in sleeps]) 
print(res)

这是一个Keyerror

2 个答案:

答案 0 :(得分:0)

要修改的密钥在dict定义中具有冗余空间

"durationInSeconds "
                  ^

答案 1 :(得分:0)

哈希和比较考虑了空格。如果它们彼此相邻打印,可能更容易发现差异:

"durationInSeconds "
"durationInSeconds"

第一个有一个尾随空格。

>>> hash(s1) == hash(s2)
False
>>> s1 == s2
False

所以他们彼此不相同,这也解释了KeyError。要修复它,您需要删除字典中的尾部空格,或者使用尾部空格查找键。例如:

>>> res = sum([x["durationInSeconds "] for x in sleeps]) 
>>> print(res)
31740