将字符串作为字典键

问题描述 投票:0回答:3

我有20K对象和列表中提供的一组功能。我需要从每个对象中提取这些功能并将它们保存到字典中。每个对象有近100个功能。

例如:

# object1
Object1.Age = '20'
Object1.Gender = 'Female'
Object1.DOB = '03/05/1997'
Object1.Weight = '130lb'
Object1.Height = '5.5'

#object2
Object1.Age = '22'
Object1.Gender = 'Male'
Object1.DOB = '03/05/1995'
Object1.Weight = '145lb'
Object1.Height = '5.8'

#object3
....

以及我需要从每个对象中提取的功能列表:

features = ['Gender', 
            'DOB', 
            'Height']

我正在尝试使用指定的功能为每个对象准备一个字典,以便:

dict1 = {features[0]:Object1.features[0], features[1]:Object1.features[1], features[2]:Object1.features[2]}

dict2 = {features[0]:Object2.features[0], features[1]:Object2.features[1], features[2]:Object2.features[2]}

dict3 = ...

由于将来可能会更改功能列表,因此我需要使代码具有灵活性。我敢肯定这不是我为每个对象准备字典的方式,但我写了这个来表明问题。

我怎么写字典?

python dictionary
3个回答
0
投票

使用包含getattr调用的字典理解:

def get_features(obj, features):
    return {f: getattr(obj, f) for f in features}

0
投票

字典理解

objdict = {feature: getattr(obj, feature) for feature in features}

您必须确保要素中的字符串与对象的属性名称匹配。


0
投票

要获取字典列表:

features = ['Gender', 'DOB', 'Height']
your_objects = [Object1, Object2]  # ...
list(map(lambda el: {f: getattr(el, f) for f in features}, your_objects))

由于您有很多对象,因此迭代地图对象而不将其强制转换为list可能很方便。

© www.soinside.com 2019 - 2024. All rights reserved.