有一个字符串作为字典键

2024-04-20 05:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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 = ...

由于功能列表可能会在未来发生变化,我需要的代码是灵活的。我肯定这不是我为每个对象准备字典的方法,但我写这篇文章是为了说明这个问题。你知道吗

我怎么写字典?你知道吗


Tags: 对象功能列表age字典特征genderfemale
3条回答

词典理解

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

必须确保features中的字符串与对象的属性名匹配。你知道吗

要获取词典列表,请执行以下操作:

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

因为您有很多对象,所以可以方便地遍历map对象,而不必将其强制转换为list。你知道吗

getattr调用中使用dict:

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

相关问题 更多 >