【问题标题】:KeyError when returning all values of 1 key based on set of 2 keys基于 2 个键的集合返回 1 个键的所有值时出现 KeyError
【发布时间】: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


    【解决方案1】:

    我假设您在 sample_data 中打错了字,y{1/2} 的键是 param_two 而不是 param_one(键在字典中必须是唯一的,param_one 已用于 @987654326 @)


    创建sample_data 变量后,您可以通过执行以下操作根据param_one / param_two 对值进行分组:

    from collections import defaultdict
    
    def groupby_params(sample_data):
        results = defaultdict(list)
        
        for s in sample_data:
            results[f"{s['param_one']}, {s['param_two']}"].append(s["distro"])
        
        return [{k: v} for k, v in results.items()]
    

    这将为您提供预期的输出:

    sample_data = [{'param_one': 'x1', 'param_two': 'y2', 'distro': 'test1'},
                   {'param_one': 'x1', 'param_two': 'y2', 'distro': 'test2'},
                   {'param_one': 'x2', 'param_two': 'y1', 'distro': 'test3'},
                   {'param_one': 'x2', 'param_two': 'y1', 'distro': 'test4'}]
    
    groupby_params(sample_data)
    
    [{'x1, y2': ['test1', 'test2']}, {'x2, y1': ['test3', 'test4']}]
    

    【讨论】:

    • 这适用于示例数据,但由于某种原因,我在从 mongo 提取数据时仍然收到 keyErrors。
    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多