gpt4 book ai didi

python - 如何使用函数将字典的值添加到Python中

转载 作者:太空宇宙 更新时间:2023-11-03 20:00:36 25 4
gpt4 key购买 nike

import csv

def statistics():
statistics2 = {}
with open("BLS_private.csv") as f:
reader = csv.reader(f)
for row in reader:
statistics2 = row

return statistics2


statistics()

字典样本数据:

['2005', '110718', '110949', '111094', '111440', '111583', '111844', '112124', '112311', '112395', '112491', '112795', '112935']
['2006', '113250', '113535', '113793', '113958', '113965', '114045', '114203', '114348', '114434', '114439', '114628', '114794']

如何将除字典中的第一个值之外的所有值连续添加到一起?

第一个值始终是年份;就像示例数据中我有 2005 年和 2006 年。我不需要添加年份。

然后我想将行中之后的所有值加在一起。我该怎么做?

(我也有很多年了)

最佳答案

欢迎来到 StackOverflow :)

您可以通过利用 list.pop(index) 获取列表中的第一项作为键,并使用列表理解来计算剩余值的总和来实现此目的。

    ## Assign variable for dictionary ##
dictionary = {}

## Data assuming it is formatted as lists within a list ##

data = [['2005', '110718', '110949', '111094', '111440', '111583', '111844', '112124', '112311', '112395', '112491', '112795', '112935'],
['2006', '113250', '113535', '113793', '113958', '113965', '114045', '114203', '114348', '114434', '114439', '114628', '114794']]

## Iterate over all lists within your data list
for i in data:

## Utilize list.pop(index) to grab and remove the first item in the list (Index 0)
key = i.pop(0)

## Create a key in the dictonary using the value we popped off the list
## Sum all values left in the list as an integer if it is a digit
dictionary[key] = sum([int(v) for v in i if v.isdigit()])

## Result

dictionary
{'2005': 1342679, '2006': 1369392}

关于python - 如何使用函数将字典的值添加到Python中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59260200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com