Skip to main content
 首页 » 编程设计

python之将值合并到有序字典中的一个键

2024年09月07日8kuangbin

所以我想知道是否有比我现在实现的合并有序字典值的解决方案更优雅的解决方案。

我有一个有序的字典,看起来像这样

'fields': OrderedDict([ 
    ("Sample Code", "Vendor Sample ID"), 
    ("Donor ID", "Vendor Subject ID"), 
    ("Format", "Material Format"), 
    ("Sample Type", "Sample Type"), 
    ("Age", "Age"), 
    ("Gender", "Gender"), 
    ("Ethnicity/ Race", "Race"), 
]), 

如果我传入一个像这样的参数作为一个列表

[2,3] or [2,4,5] 

有没有一种优雅的方法可以将值合并到一个新键下

[2,3], "Random_Key" 

会回来

'fields': OrderedDict([ 
        ("Sample Code", "Vendor Sample ID"), 
        ("Donor ID", "Vendor Subject ID"), 
        **("Random Key", "Material Format Sample Type"),** 
        ("Age", "Age"), 
        ("Gender", "Gender"), 
        ("Ethnicity/ Race", "Race"), 
    ]), 

同时删除字典中的键?

请您参考如下方法:

这也可以用生成器很好地完成。

如果不必压缩,此生成器会生成 key 项对,如果已压缩,则会将项保存到最后一个条目,然后生成它,并使用新 key 和已保存的项连接。

使用生成器可以构造一个新的 OrderedDict。

from collections import OrderedDict     
 
def sqaushDict(d, ind, new_key): 
    """ Takes an OrderedDictionary d, and yields its key item pairs,  
    except the ones at an index in indices (ind), these items are merged  
    and yielded at the last position of indices (ind) with a new key (new_key) 
    """ 
    if not all(x < len(d) for x in ind): 
        raise IndexError ("Index out of bounds") 
    vals = [] 
    for n, (k, i), in enumerate(d.items()): 
        if n in ind: 
            vals += [i] 
            if n == ind[-1]: 
                yield (new_key, " ".join(vals)) 
        else: 
            yield (i, k) 
 
d = OrderedDict([ 
    ("Sample Code", "Vendor Sample ID"), 
    ("Donor ID", "Vendor Subject ID"), 
    ("Format", "Material Format"), 
    ("Sample Type", "Sample Type"), 
    ("Age", "Age"), 
    ("Gender", "Gender"), 
]) 
 
t = OrderedDict(squashDict(d, [2, 3], "Random")) 
print(t)