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

Python中dict(zip())合并JSON导入列表异常问题求助

问题原因及解决办法

问题本质

Python 的字典(dict)核心规则是键必须唯一,当你用 dict(zip(l1, l2)) 转换时,如果 l1 里存在重复的键,后面的键值对会直接覆盖前面的。

看你的输入列表:

  • l1 里 grant_type、client_id、scope 各出现两次
  • 对应 l2 里的前三个值 client_credentials、AIS、{{client_id}},全被后面的 authorization_code、{{scope}}:{{consents_id}}、{{client_id}} 覆盖了——这就是输出里看不到前三个值的原因。

和双大括号 {{ }} 完全无关,它只是普通字符串的一部分,不会影响字典的键值处理逻辑。

解决方案

根据你的需求,有两种常用处理方式:

1. 保留所有键值对(用列表存元组)

如果只是想完整保留所有配对关系,不用转成字典,直接把 zip 的结果转成列表就行:

l1 = ['grant_type', 'scope', 'client_id', 'client_id', 'grant_type', 'scope', 'code', 'redirect_uri']
l2 = ['client_credentials', 'AIS', '{{client_id}}', '{{client_id}}', 'authorization_code', '{{scope}}:{{consents_id}}', '{{response}}', '{{redirect_url}}']
pairs = list(zip(l1, l2))
print(pairs)

输出:

[('grant_type', 'client_credentials'), ('scope', 'AIS'), ('client_id', '{{client_id}}'), ('client_id', '{{client_id}}'), ('grant_type', 'authorization_code'), ('scope', '{{scope}}:{{consents_id}}'), ('code', '{{response}}'), ('redirect_uri', '{{redirect_url}}')]

2. 把相同键的值收集到列表里

如果需要保留相同键的所有值,可以用 collections.defaultdict 来实现:

from collections import defaultdict

l1 = ['grant_type', 'scope', 'client_id', 'client_id', 'grant_type', 'scope', 'code', 'redirect_uri']
l2 = ['client_credentials', 'AIS', '{{client_id}}', '{{client_id}}', 'authorization_code', '{{scope}}:{{consents_id}}', '{{response}}', '{{redirect_url}}']

result = defaultdict(list)
for key, value in zip(l1, l2):
    result[key].append(value)

# 可选:转成普通字典
result = dict(result)
print(result)

输出:

{'grant_type': ['client_credentials', 'authorization_code'], 'scope': ['AIS', '{{scope}}:{{consents_id}}'], 'client_id': ['{{client_id}}', '{{client_id}}'], 'code': ['{{response}}'], 'redirect_uri': ['{{redirect_url}}']}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:40:46