You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套字典列表推导式报错:NameError: name 'value' is not defined 求助

Fixing the NameError in Your List Comprehension

Hey there! The issue here is the order of your for loops in the list comprehension. In Python, list comprehensions follow the same loop order as regular nested for loops—you need to start with the outer loop first, then move to the inner one.

Your original code puts the inner loop (for v_i in value) before the outer loop (for key,value in tt.items()), which means Python tries to reference value before it’s been defined by the outer loop. That’s exactly why you’re getting the NameError.

Correct Solution

Let’s reverse the loop order to match how you’d write nested loops normally. Here’s the fixed list comprehension:

tt = {'plot1':[ {'var': 'ok__you', 'uuid': '98782098109'}, {'var': 'hdg__akj', 'uuid': '712837901'} ], 'plot2': [ {'var': 'ok__you2', 'uuid': '987820981092'}, {'var': 'hdg__akj2', 'uuid': '7128379012'} ]}

lst = [v_i['uuid'] for key, value in tt.items() for v_i in value]
print(lst)

How It Works

To make it clearer, here’s what the list comprehension translates to in regular nested loops:

lst = []
for key, value in tt.items():
    # First, grab each list of dictionaries from the main dict
    for v_i in value:
        # Then, iterate over each dict in that list to extract the uuid
        lst.append(v_i['uuid'])

Running the corrected code will output your desired list of uuids:
['98782098109', '712837901', '987820981092', '7128379012']

内容的提问来源于stack exchange,提问作者JohnJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:06:50