繁体   English   中英

如何迭代 2 JSON 列表(混合字典和列表),匹配特定值并打印另一个值

[英]How do I iterate over 2 JSON lists (mix dict and list), match specific values and print another value

我有 2 个单独的 JSON 列表(带有字典)。 我的目标是,我想遍历 list2“currentUser”,获取值,在 list1 中搜索这些值,然后 output 打印“firstName”的值

例如 liste2: "currentUser": 123, liste1: "id": "123", --> "firstName": "Lisa",

list1 = {
    "X-API-KEY": "XyZzahZaksksXXXYYYOOO000",
    "user": {
                "email": "Lisa@BLA.com",
                "firstName": "Lisa",
                "id": "123",
    },
    "Flat": {
        "city": "Munich",
        "country": "2",
        "countryCode": "DEU",
        "currency": "EUR",
        "date": "1587671397",
        "flatmates": [
            {
                "email": "Lisa@BLA.com",
                "firstName": "Lisa",
                "id": "123",
            },
            {
                "email": "Max@BLA.com",
                "firstName": "Max",
                "id": "124",
            },
            {
                "email": "Hannah@BLA.com",
                "firstName": "Hannah",
                "id": "125",
            },
            {
                "email": "Kai@BLA.com",
                "firstName": "Kai",
                "id": "126",
            }
        ],
        "founderId": "123",
        "id": "99999",
        "image": "",
        "name": "ABC",
        "postCode": "000000",
    }
}
list2 = [
    {
        "creationDate": 1587671663,
        "currentUser": 123,
        "id": 1717134,
        "title": "Do this",
        "users": [
            124,
            126
        ]
    },
    {
        "creationDate": 1587671663,
        "currentUser": 126,
        "id": 1717134,
        "title": "Do that",
        "users": [
            123,
            125
        ]
    },
    {
        "creationDate": 1587671821,
        "currentUser": 124,
        "id": 1717134,
        "title": "Clean this",
        "users": [
            125,
            122
        ]
    },
    {
        "creationDate": 1587671801,
        "currentUser": 123,
        "id": 1717134,
        "title": "Clean that",
        "users": [
            124,
            126
        ]
    }
]

我是 python 的新手。我有几个头脑问题,因为它混合了列表和字典,以及如何匹配/搜索 2 个单独的列表/字典的值

到目前为止我得到了什么:迭代“CurrentUser”

for user in liste2:
    print(user["currentUser"])

有没有人有一些方法?

在没有其他模块的纯 python 中。

for user in list2:
    for mate in list1['Flat']['flatmates']:
        if user['currentUser'] == int(mate['id']):
            # You found the person now execute this code...

需要注意的一件事是,在您的 list1 中,您的室友 ID 不是 integer 而是一个字符串。 因此,您必须将其转换为 int 才能比较两者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM