【发布时间】:2021-06-22 10:44:48
【问题描述】:
我正在尝试查询 mongo 数据库并根据数据库中的一组两个键返回一个 JSON 键的所有值。我在下面的尝试,它返回
KeyError: ('test1', 'test2')
def distros(
mongo_uri: str,
mongo_source_db: str,
mongo_source_collection: str) -> Dict[str, List[str]]:
distros_per_param= OrderedDict()
mongo = pymongo.MongoClient(mongo_uri)
db = mongo.get_database(mongo_source_db)
col = db.get_collection(mongo_source_collection)
query = {}
total = col.count_documents(query)
cursor = col.find(query)
for doc in tqdm(cursor, total=total, desc='distributions'):
param_one = doc['param_one']
param_two = doc['param_two']
if param_type not in distributions_per_type:
distributions_per_param[param_one] = set()
if param_value not in distributions_per_type:
distributions_per_param[param_two] = set()
distro_value = str(doc['distro']).strip().lower()
if distro_value:
distributions_per_param[param_type, param_value].add(distro_value)
print(doc)
index = {k: sorted(v) for k, v in distributions_per_param.items()}
return index
数据是从 mongo 查询的 json 文档列表
sample_data = [{'param_one': 'x1', 'param_one': 'y2', 'distro': 'test1'},
{'param_one': 'x1', 'param_one': 'y2', 'distro': 'test2'},
{'param_one': 'x2', 'param_one': 'y1', 'distro': 'test3'},
{'param_one': 'x2', 'param_one': 'y1', 'distro': 'test4'}]
我需要结果数据看起来像
result = [{'x1, y2': ['test1','test2']},
{'x2, y1': ['test3','test4']}]
【问题讨论】:
标签: python dictionary set