2014-09-21 33 views
0

檢索字典的名字我有字典的名單,我想從像一個循環檢索他們的名字:的Python:從列表

for d in list_dicts: 
    print d.name 

list_dicts = [dic1, dic2] 
d.name = dic1 

是否可能,如何?謝謝

+0

您對名稱的含義是什麼?你的意思是鍵或值ex:'{key:value}'或者你想要字典的名字?你的代碼也有很多錯誤! – Kasramvd 2014-09-21 18:58:23

+1

我想他是在談論字典變量名稱,'dic1'和'dic2',但這些只是參考,所以,不,你不能得到他們的「名字」 – ZekeDroid 2014-09-21 19:02:05

回答

2

dic1dic2是變量名稱。他們沒有意義。事實上,你可以這樣做:

dic1 = {1:2, 3:4} 
dic2 = dic1 
list_dicts = [dic1, dic2] 

而這裏的列表包含兩個引用相同的字典!

如果你真的需要一個名字,你可以簡單地把它添加到字典中(有點哈克,但只要將正常運行,關鍵是唯一的):

dic1['name'] = 'dic1' 

你可以在包裝他們倆類:

class NamedDct(object): 
    def __init__(self, dct, name): 
     self.dct = dct 
     self.name = name 
dic1 = NamedDct(dic1, 'dic1') 

或者你可以從字典繼承(請注意,這是一個退化的例子,沒有深入到細節):

class NamedDct(dict): 
    def __init__(self, name): 
     self.name = name 
     super(NamedDct, self).__init__() 
dic1_new = NamedDct('dic1') 
dic1_new.update(dic1) 
+0

我想我會去繼承。謝謝 !;) – 2014-09-21 19:07:12

+0

筆記;就像在這個例子中實現的那樣,如果這對你來說很重要,你將會在建造時失去所有各種初始化'dict'的東西。 – aruisdante 2014-09-21 19:09:41

+0

@aruisdante真。只是想舉一個例子,不要深究。 – Korem 2014-09-21 19:10:58

0

假如你有這樣的字典清單:

DIC1:{ 「名」: 「名1」,...} DIC2:{ 「名」: 「名稱2」,...}

以及像這樣的一個列表: list_dicts = [dic1,dic2]

訪問字典字段的方法是文字表示法(帶括號)。

for d in list_dicts: 
    print d["name"] 
+0

這似乎並不適用於我,跟隨你示例非常精確,我被告知'TypeError:字符串索引必須是整數,而不是str'。看來python想要相信d是一個列表而不是字典。 – jg3 2015-02-24 00:43:58

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'}