【问题标题】:How can i loop through this dict and grab the data i want based on value?我如何遍历这个字典并根据值获取我想要的数据?
【发布时间】:2020-01-10 07:30:31
【问题描述】:

嗨,我有一个从请求中获取的 json 变量,我想循环遍历项目以根据键和值获取我想要的项目,例如: 从 key="abc" 和 value=True 的数据中选择行 但我也想获取该行的 id,以便我可以获取第二行数据 我知道这很混乱,但我试图解释 请看下面的图片

我对 python 还很陌生,从 nodejs “地狱”切换后,我发现 python 方式更容易更好,json/dict 解码很痛苦,但仍然可以管理呵呵 我不知道如何做到这一点 以下是我从 api 获得的实际代码

response = requests.post('https://www.com', headers=tmp, data=data).json()
            x = json.dumps(response, ensure_ascii=False)
            print x['aaa']

上面的代码可以打印项目,但我想循环访问它们以从 a>id 和 b>id 获取所需的数据,其中 a.is_data_real = True 谢谢

【问题讨论】:

标签: python json python-2.7 list dictionary


【解决方案1】:

首先将x['bbbb'] 转换为字典,其中键为id,值为 bbbb 行 - 这使得通过 id 查找行更快,因为我们不必迭代,我们可以只进行 dict 查找

b_map = {b['id']:b for b in x['bbbb']}

现在您可以使用推导式来获取“data_is_real”为真的所有“a”行,并像这样从 b 中添加匹配行

[(a, b_map[a['id']]) for a in x['aaa'] if a['data_is_real']]

【讨论】:

  • 您好,再次感谢您的回复,我决定做一个 for 循环并设法轻松获取数据,上面的答案似乎有点难大声笑下面的代码供参考:for bbbb in jclean['bbbb']: if bbbb['id'] == 10 and bbbb['is_value'] == True: id = bbbb['id'] for aaaa in jclean['aaaa']: if aaaa['1_id'] == id or aaaa['2_id'] == id: print aaaa['id'] Works就像一个魅力,我无法在不破坏任何东西的情况下清理俄语文本以工作
  • 这是来自请求帖子的代码:s = response.text jclean = json.loads(s.encode('utf-8'))
【解决方案2】:

如果我正确理解您的意图,以下内容应该适合您。这是在 Python 2.7.15rc1 上测试的:

# Example Data
data = {"aaa":[{"etrert":619337442,"home":"werewrw","id": 595506140083,"is_data_real": True},{"etrert":719337432,"home":"filler","id": 695506149983,"is_data_real": True}, {"etrert":719337432,"home":"filler","id": 795506149983,"is_data_real": False}], "bbb":[{"roi":0,"qweqweqe":1,"id": 595506140083},{"roi":1,"qweqweqe":1,"id": 695506149983},{"roi":0,"qweqweqe":1,"id": 59550999983},{"roi":1,"qweqweqe":3,"id": 595506140083}]}

# Create a Filter Function Creator
# If it finds the id, only returns it if "is_data_real" is True
def create_id_filter(id_needed):
    def id_filter(d):
        if d["id"] == id_needed and d["is_data_real"] == True:
            return True
        else:
            return False
        return
    return id_filter

# Create a filter for any id number you want
id_filter = create_id_filter(595506140083)

# Filter the "aaa" objects using the filter created above
real_a = filter(id_filter, data["aaa"])

# Use list comprehension to pull out just the ids
a_ids = [x['id'] for x in real_a]

# Use list comprehension to pull all b objects that match the id
b_matches = [x for x in data["bbb"] if x["id"] in a_ids]

print b_matches
# [{'roi': 0, 'qweqweqe': 1, 'id': 595506140083}, {'roi': 1, 'qweqweqe': 3, 'id': 595506140083}]

另外,如果你有一个 id 列表,你可以像这样从 "bbb" 获得所有结果:

def get_b_matches(request_data, id_list):
    result = []
    for i in id_list:
        id_filter = create_id_filter(i)
        real_a = filter(id_filter, request_data["aaa"])
        a_ids = [x['id'] for x in real_a]
        b_matches = [x for x in request_data["bbb"] if x["id"] in a_ids]
        result.extend(b_matches)
    return result

get_b_matches(data, [595506140083, 695506149983])
# [{'roi': 0, 'qweqweqe': 1, 'id': 595506140083}, {'roi': 1, 'qweqweqe': 3, 'id': 595506140083}, {'roi': 1, 'qweqweqe': 1, 'id': 695506149983}]

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2021-12-20
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2020-01-04
    相关资源
    最近更新 更多