我的JSON结构是这样的,我希望通过检查列表中每个字典的driverKey
来创建新的列表
{
"RDBMS": [
{
"userName": "a",
"entityName": "entity1",
"connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;",
"databaseName": "database1",
"driverKey": "PostgreSQL Unicode"
},
{
"userName": "b",
"entityName": "entity2",
"connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;",
"databaseName": "database1",
"driverKey": "PostgreSQL Unicode"
},
{
"userName": "a",
"entityName": "entity3",
"connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;",
"databaseName": "database1",
"driverKey": "SQL Server"
}
]
}
预期产量:
{
"PostgreSQL": [
{
"userName": "a",
"entityName": "entity1",
"connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;",
"databaseName": "database1",
"driverKey": "PostgreSQL Unicode"
},
{
"userName": "b",
"entityName": "entity2",
"connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;",
"databaseName": "database1",
"driverKey": "PostgreSQL Unicode"
}
],
"SQL SERVER": [
{
"userName": "a",
"entityName": "entity1",
"connectionString": "DRIVER={PostgreSQL Unicode};DATABASE=database1;UID=uid1;PWD=password;SERVER=127.0.0.1;SID=null;PORT=5432;",
"databaseName": "database1",
"driverKey": "PostgreSQL Unicode"
}]
}
我尝试过不同的方法,但是字典里的"connectionString"
给了我不同的输出。
循环列表和获取项目并不能解决我的问题。有什么建议吗
你需要两个环。每个键一个,每个键的列表值另一个。每次迭代都附加到新字典
或者,使用
defaultdict
:defaultdict对于很多数据来说效率略高一些(不管每次是否必须创建和返回列表,
dict.setdefault
都不必要地创建和返回列表)根据您的注释,外部循环不是必需的,但是编写在输入更改时不容易中断的代码总是很好的
要创建dict,需要迭代项,然后将其分配给unique键
相关问题 更多 >
编程相关推荐