Skip to main content
 首页 » 编程设计

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

2025年02月15日10lidabo

我有这个代码:

    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)]} 

我想做的是根据键将上述字典中的a和b属性提取到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]}