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

Python 将值合并到有序Dict中的一个键,python,python-3.x,ordereddictionary,Python,Python 3.x,Ordereddictionary,所以我想知道,对于我现在实现的合并有序dict值的方法,是否有一个更优雅的解决方案 我有一个像这样的命令命令 'fields': OrderedDict([ ("Sample Code", "Vendor Sample ID"), ("Donor ID", "Vendor Subject ID"), ("Format", "Material Format"), ("Sample Type", "Sample Type"), ("Age", "Age"),

所以我想知道,对于我现在实现的合并有序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"),
]),
如果我像列表一样传入一个参数

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

同时删除字典中的键

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

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")

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

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

  • 获取密钥列表
  • 找到要与以下项合并的键的索引
  • 删除字典的下一个键
  • 创建包含
    d
    项的列表
  • 使用存储索引处的新值更改此列表
  • 从中重建一个
    OrderedDict
这样(我删除了一些键,因为它缩短了示例):

结果:

OrderedDict([(“样本代码”、“供应商样本ID”)、(“捐赠者ID”、“供应商主体ID”)、(“格式”、“材料格式”)、(“新密钥”、“样本类型年龄”)、(“性别”、“性别”))


这也可以通过一个生成器很好地完成

如果不需要挤压,此生成器将生成密钥项对,如果需要挤压,则会将这些项保存到最后一个条目,然后生成新密钥,并将保存的项合并在一起

使用该生成器,可以构建新的OrderedICT

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)
从集合导入订单数据
def sqaushDict(d、ind、新_键):
“”接受OrderedDictionary d,并生成其键项对,
除了索引(ind)中索引处的项目外,这些项目将合并
并在索引(ind)的最后位置使用新键(new_键)生成
"""
如果不是全部(x
2018年至少有一个关于词典的有趣问题。我希望你把输入数据再减少一点。太多的价值观淹没了开始和结束之间的差异。@Jean Françoisfare我能做到!看:这样看起来更好这绝对是我想要的谢谢!
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)
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)