如何在嵌套的Python词典中找到特定的匹配?

时间:2014-01-03 23:19:01

标签: python loops python-2.7 dictionary iteration

我尝试在嵌套的Python词典中找到深度匹配。我正在寻找一个特定的昵称来查找 player_id 。我找到的昵称存储在名称(名称=“0”)中。

我正在尝试通过“if name in value:”找到匹配。

重新解释我的问题:如何检索其中一个值与我的搜索匹配的字典?

json_file = r.text
dct = json.loads(json_file)
for key, value in dct.iteritems():
    if "data" in key:
        for minilist in value:
            for key, value in minilist.iteritems():
                if name in value:

我的数据如下(我通过json模块成功转换它):

{"status":"ok","count":3,"data":
[
{"nickname":"zero10","account_id":500749494}, 
{"nickname":"Zero100","account_id":505683972},
{"nickname":"zero100v1","account_id":502108240}
]}

我希望最终结果看起来像

{"nickname":"zero10","account_id":500749494}

3 个答案:

答案 0 :(得分:0)

我修改了你的代码,而不是100%确定我是否理解了这个问题,但这里是:

<强>代码:

name = "zero10"

d1 = {"status":"ok", "count":3, "data":
[{"nickname":"zero10", "account_id":500749494},
{"nickname":"Zero100", "account_id":505683972},
{"nickname":"zero100v1", "account_id":502108240}
]}

result = None
for key, value in d1.iteritems():
    if "data" == key:
        for dic2 in value:
            if dic2['nickname'] == name:
                result = dic2['account_id']

print result

<强>输出:

>>> 500749494

如果您想获取字典,请使用result = dic2['account_id']

更改result = dic2

<强>输出:

>>> {'nickname': 'zero10', 'account_id': 500749494}

备注: 只有在d1中“数据”值的字典对中,才能使用此选项:{"nickname" : "...", "account_id" : ...}

答案 1 :(得分:0)

这会有用吗?

name = 'zero10'
for key, value in d.iteritems():
    if "data" in key:
        for minilist in value:
            #print minilist
            if minilist['nickname'] == name:
                print minilist

结果如下:

{'nickname': 'zero10', 'account_id': 500749494}

答案 2 :(得分:0)

你的生活比你需要的更难。我打破了代码,将响应验证与寻找玩家分开。这使得它更容易理解(至少对我的大脑而言))。函数dict.get(key, default)避免显式data检查。

def find_player(wanted_nick, data):
    for player in data:
        if player["nickname"] == wanted_nick:
            return player
    return None

print(find_player("zero10", dct.get("data", [])))

输出:

{'nickname': 'zero10', 'account_id': 500749494}

另请注意"data" in key是危险的,因为您正在进行包含检查。如果你的响应字典包含一个包含单词“data”的键,它也会评估真值,即它看起来如下:`{“no_data_found”:True}。不是你想要的。