【问题标题】:Iterating over a list of nested dictionaries遍历嵌套字典列表
【发布时间】:2015-12-06 01:33:51
【问题描述】:

您好,我正在尝试遍历此列表并访问嵌套字典中的特定值

[{'customer': {'name': 'Karl'}}, {'customer': {'name': 'Smith'}}]

使用这个列表理解

[d for d in Account.accountList if d['customer']['name'] == 'smith']

但我得到了这个TypeError: string indices must be integers,我知道这与 python 认为我的列表是一个字符串有关,但它绝对是一个列表

>>> type(Account.accountList)
 <class 'list'>

我尝试过嵌套 for 循环,但我不断收到此错误,不胜感激。..

class Customer:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return repr(self.__dict__)

class Account:
    accountList = []
    def __init__(self, name):
        self.customer = Customer(name)
        Account.accountList.append(self)

    def __repr__(self):
        return repr(self.__dict__)

    def __getitem__(self, i):
        return i

【问题讨论】:

  • 那些不是字典...

标签: python dictionary nested


【解决方案1】:
[d for d in Account.accountList if d.customer.name == 'smith']

你很亲密

问题来了

def __getitem__(self, i):
    return i

你可以在下面看到发生了什么

MyClass["whatever"] == "whatever" #True
"whatever"["asd"] #error

我认为你可以使用

def __getitem__(self,item):
    return getattr(self,item)

【讨论】:

  • 是的... d 是Account 的一个实例... 不是dict ... 并且__getitem__ 返回一个字符串... 所以是的,无法访问他的客户属性......也不是它的名称属性......(因为我可以告诉客户根本没有实现__getitem__......最多OP可以以d["customer"].name访问它(如果他们修复Account.__getitem__,如果他们向客户添加__getitem__,然后他们当然可以完全通过指示而不是属性查找来访问它)
  • @JoranBeasley 为什么 d 是Account 的实例? OP 正在遍历存储在Account.accountList 中的字典列表。
  • 谢谢你是对的,他们是我帐户的问题。__getitem__ 是导致字符串错误的原因。我也给客户添加了__getitem__,我可以像你说的那样使用索引访问客户实例。
  • 太棒了...如果此答案有助于解决您的问题,请随时点赞并接受...如果您仍需要帮助,请进一步解释
  • mmm 可能是 print next(d for d in Account.accountList if d['customer']['name'] == 'smith')(假设您已纠正了 __getitem__ 的问题
【解决方案2】:

你正在尝试的实际上对我有用!

输入:

details = [{'customer': {'name': 'Karl'}}, {'customer': {'name': 'Smith'}}]

[x for x in details if x['customer']['name'] == 'Smith']

结果: [{'customer': {'name': 'Smith'}}]

编辑: 仔细看这条线... Account.accountList.append(self)

您似乎将一个对象附加到AccountList,而不是您期望的字典,因为self 是一个对象。试试:

Account.accountList.append({'customer': {'name': name}})

【讨论】:

  • 它们不是字典,它们是(您在 OP 中看到的列表)来自他的帐户和客户类的代表……详细信息不是字典列表……我向你保证……我的答案是正确的
  • @JoranBeasley 是的,谢谢。不过我的措辞有点不同。
  • 在这种情况下有一个 +1 为他提供一种使其工作的方法:P
  • 谢谢哥们,解决方案也不错,如果我想添加多个类实例,我会继续添加到 append 方法中,例如Account.accountList.append({'customer': {'name': name}}, {'cash':{'balance': balance)}
  • @cyclopse87 你可以这样做,但效率很低。最好将对象实例附加到列表中 - 并使用对象而不是字典。这样,如果您添加新属性,您就不会忘记更新字典。我的回答纯粹是为了说明为什么您的列表理解不起作用:)
猜你喜欢
  • 1970-01-01
  • 2020-11-13
  • 2012-07-09
  • 2021-03-19
  • 1970-01-01
  • 2017-07-25
相关资源
最近更新 更多