gpt4 book ai didi

python - 从字典中的类实例中提取值

转载 作者:太空宇宙 更新时间:2023-11-04 05:12:48 25 4
gpt4 key购买 nike

我有这个代码:

    class B():

def __init__(self, valueA, valueB ):
self.valueA = valueA
self.valueB = valueB


def __repr__(self):
return 'B({0},{1})'.format(self.valueA, self.valueB)

我的数据是:

thedata = {'a': [B(1, 0.1),B(2, 0.2)],
'b': [B(3, 0.3),B(4, 0.4)]}

我想做的是根据键将上述字典中的ab属性提取到2个新字典中。

所以,我想要:

thedata_a_valueA = {'a':[1, 2]}
thedata_a_valueB = {'a':[0.1, 0.2]}
thedata_b_valueA = {'b':[3, 4]}
thedata_b_valueB = {'b':[0.3, 0.4]}

最后我想要 2 部词典:

newdict_valueA = {'a':[1, 2], 'b':[3,4]}
newdict_valueB = {'a':[0.1, 0.2], 'b':[0.3,0.4]}

一个解决方案是使用列表,但我必须创建相当多的列表,遍历它们,追加等

thedata 是否有任何更清洁/更快的解决方案?

最佳答案

像这样的东西会起作用:

# Starting from two empty dictionaries
newdict_valueA, newdict_valueB = {}, {}

# Iterate over the key/value pairs of the data
for key, value in thedata.items():
# assign to the same key of each result dictionary a list of
# the valueA for each B item in the value of the original dictionary
newdict_valueA[key] = [item.valueA for item in value]
newdict_valueB[key] = [item.valueB for item in value]

newdict_valueA:

{'a': [1, 2], 'b': [3, 4]}

新字典值B:

{'a': [0.1, 0.2], 'b': [0.3, 0.4]}

关于python - 从字典中的类实例中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42574707/

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