将值合并到有序Di中的一个键

2024-04-19 03:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想知道,对于我现在实现的合并有序dict值的方法,是否有一个更优雅的解决方案

我有一个像这样的有序字典

'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"),
]),

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

^{pr2}$

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

[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"),
    ]),

同时删除字典中的键?在


Tags: sample方法idformatfieldsage字典type
3条回答

您可以通过对索引进行降序排序来优化这一点,然后可以使用dict.pop(key,None)立即检索并删除键/值,但我决定不这样做,按照indices中出现的顺序追加值。在

from collections import OrderedDict
from pprint import pprint

def mergeEm(d,indices,key):
    """Merges the values at index given by 'indices' on OrderedDict d into a list.        
    Appends this list with key as key to the dict. Deletes keys used to build list."""

    if not all(x < len(d) for x in indices):
        raise IndexError ("Index out of bounds")

    vals = []                      # stores the values to be removed in order
    allkeys = list(d.keys())
    for i in indices:
        vals.append(d[allkeys[i]])   # append to temporary list
    d[key] = vals                  # add to dict, use ''.join(vals) to combine str
    for i in indices:              # remove all indices keys
        d.pop(allkeys[i],None)
    pprint(d)


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"),
    ("Sample Type", "Sample Type"),
    ("Organ", "Organ"),
    ("Pathological Diagnosis", "Diagnosis"),
    ("Detailed Pathological Diagnosis", "Detailed Diagnosis"),
    ("Clinical Diagnosis/Cause of Death", "Detailed Diagnosis option 2"),
    ("Dissection", "Dissection"),
    ("Quantity (g, ml, or ug)", "Quantity"),
    ("HIV", "HIV"),
    ("HEP B", "HEP B")
])
pprint(fields)
mergeEm(fields, [5,4,2], "tata")

输出:

^{pr2}$

不知道有没有优雅的方式。OrderedDict有一个move_to_end方法在开始或结束时移动关键点,但不是在随机位置。在

我会尽量提高效率,尽量减少循环次数

  • 把钥匙列出来
  • 找到要与下面的键合并的键的索引
  • 删除字典的下一个键
  • 使用d项创建列表
  • 使用存储索引处的新值更改此列表
  • 从中重建OrderedDict

像这样(我删除了一些键,因为它缩短了示例):

from collections import OrderedDict

d = OrderedDict([
    ("Sample Code", "Vendor Sample ID"),
    ("Donor ID", "Vendor Subject ID"),
    ("Format", "Material Format"),
    ("Sample Type", "Sample Type"),
    ("Age", "Age"),
    ("Gender", "Gender"),
])

lk = list(d.keys())
index = lk.index("Sample Type")
v = d.pop(lk[index+1])

t = list(d.items())
t[index] = ("new key",t[index][1]+" "+v)

d = OrderedDict(t)

print(d)

结果:

OrderedDict([('Sample Code', 'Vendor Sample ID'), ('Donor ID', 'Vendor Subject ID'), ('Format', 'Material Format'), ('new key', 'Sample Type Age'), ('Gender', 'Gender')])

这也可以很好地与发电机。在

如果不必压缩键项对,则此生成器将生成键项对;如果已压缩,则将项保存到最后一个项,然后生成它,并将新键与保存的项联接起来。在

有了这个生成器,就可以构造一个新的有序dict。在

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)

相关问题 更多 >