【问题标题】:Find the index of a nested dict within a list base on the dict's nested value根据字典的嵌套值在列表中查找嵌套字典的索引
【发布时间】:2021-04-09 20:58:21
【问题描述】:

我有一个字典列表

[{"id":1, "name": "jane", "contact": {"email": "jane@gmail.com", "phone": "8179482938"}},
{"id":2, "name": "john", "contact": {"email": "john@gmail.com", "phone": "8179482937"}},
{"id":3, "name": "june", "contact": {"email": "june@gmail.com", "phone": "8179482936"}}]

我怎样才能找到简的索引只给她的电话号码(8179482938)?

【问题讨论】:

    标签: python list dictionary indexing


    【解决方案1】:

    这很简单。你循环遍历列表,直到找到你想要的。

    def get_name(phone):
        for i, row in enumerate(list_of_dicts):
            if row['contact']['phone'] == phone:
                return i
    

    【讨论】:

    • 呸,我以为我读到了“我怎样才能找到简。”。我会解决的。
    【解决方案2】:

    要获得索引,您可以这样做(lst 是您的问题列表):

    idx = next(i for i, d in enumerate(lst) if d["contact"]["phone"] == "8179482938")
    print(idx)
    

    打印:

    0
    

    【讨论】:

      【解决方案3】:

      这个:

      book = [{"id":1, "name": "jane", "contact": {"email": "jane@gmail.com", "phone": "8179482938"}},
      {"id":2, "name": "john", "contact": {"email": "john@gmail.com", "phone": "8179482937"}},
      {"id":3, "name": "june", "contact": {"email": "june@gmail.com", "phone": "8179482936"}}]
      
      for item in book:
          if item['contact']['phone'] == '8179482938':
              print(item['id'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        • 1970-01-01
        相关资源
        最近更新 更多