我有一个词典列表,我想从一个循环中检索他们的名字:
for d in list_dicts:
print d.name
list_dicts = [dic1, dic2]
d.name = dic1
有可能吗?谢谢
答案 0 :(得分:2)
dic1
或dic2
是变量名称。它们毫无意义。事实上,你可以这样做:
dic1 = {1:2, 3:4}
dic2 = dic1
list_dicts = [dic1, dic2]
此处列表包含对同一字典的两个引用!
如果你真的需要一个名字,你可以简单地将它添加到字典中(有点hacky,但只要密钥是唯一的,它就应该工作):
dic1['name'] = 'dic1'
你可以将它们包装在一个类中:
class NamedDct(object):
def __init__(self, dct, name):
self.dct = dct
self.name = name
dic1 = NamedDct(dic1, 'dic1')
或者你可以从dict继承(请注意这是一个退化的例子,没有深入细节):
class NamedDct(dict):
def __init__(self, name):
self.name = name
super(NamedDct, self).__init__()
dic1_new = NamedDct('dic1')
dic1_new.update(dic1)
答案 1 :(得分:1)
您可能希望使用namedtuple来完成此类操作。
命名元组允许构造一个轻量级的名称/数据组合(以元组的Python子类的形式),这对于这个用例是完美的。
假设我们想要一个附加到名称的字典。
(使用verbose=True
打印出整个班级以供检查。在正常使用中,不包括......)
>>> from collections import namedtuple
>>> NamedDict = namedtuple('NamedDict', 'name data', verbose=True)
class NamedDict(tuple):
'NamedDict(name, data)'
__slots__ = ()
_fields = ('name', 'data')
def __new__(_cls, name, data):
'Create new instance of NamedDict(name, data)'
return _tuple.__new__(_cls, (name, data))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new NamedDict object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' % len(result))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return 'NamedDict(name=%r, data=%r)' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self))
def _replace(_self, **kwds):
'Return a new NamedDict object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('name', 'data'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
return result
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
__dict__ = _property(_asdict)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
pass
name = _property(_itemgetter(0), doc='Alias for field number 0')
data = _property(_itemgetter(1), doc='Alias for field number 1')
考虑
>>> nd=NamedDict('dict1', {1:'one', 2:'two'})
>>> nd
NamedDict(name='dict1', data={1: 'one', 2: 'two'})
>>> nd.name
'dict1'
>>> nd.data
{1: 'one', 2: 'two'}
因此,您可以将名称和字典与列表中的每一对相关联:
LoT=[
('dict1', {1:'one', 2:'two'}),
('dict2', {3:'three', 4:'four'})
]
NamedDict = namedtuple('NamedDict', 'name data')
LoND=[NamedDict(*t) for t in LoT]
for d in LoND:
print(d.name, d.data)
打印:
dict1 {1: 'one', 2: 'two'}
dict2 {3: 'three', 4: 'four'}
答案 2 :(得分:0)
假设您有一个包含这样字典的列表:
dic1:{" name":" Name1",...} dic2:{" name":" Name2",...}
这样的列表: list_dicts = [dic1,dic2]
访问字典字段的方式是文字表示法(带括号)。
for d in list_dicts:
print d["name"]