Group values of a key if another key has got same values that are list type in list of dictionary

huangapple go评论68阅读模式
英文:

Group values of a key if another key has got same values that are list type in list of dictionary

问题

我有一个字典列表,

data = [{"service":"1","unit":["A","B"]},{"service":"2","unit":["A","B"]},{"service":"1","unit":["C"]}]

我希望输出如下:

output = [{"service":["1","2"],"unit":["A","B"]},{"service":["1"],"unit":["C"]}]

我尝试了不同的代码来根据另一个键的值将键值分组,但由于unit是一个列表,我不确定该如何处理。

尝试的代码:

for dd in data:
   d.setdefault(dd['service'], set()).update(dd['unit'])

newlst = [{'service':k, 'unit':list(v)} for k,v in d.items()]
print(newlst)

请帮助。

英文:

I have a list of dictionary,

  data = [{"service":"1","unit":["A","B"]},{"service":"2","unit":["A","B"]},{"service":"1","unit":["C"]}]

I want the output to be:

  output = [{"service":["1","2"],"unit":["A","B"]},{"service":["1"],"unit":["C"]}]

I tried different codes that groups the key values if the value of another key is similar, but as unit are in list, I am unsure how to deal with this.

Tried Code:

 for dd in data:
   d.setdefault(dd['service'], set()).update(dd['unit'])

 newlst = [{'service':k, 'unit':list(v)} for k,v in d.items()]
 print(newlst)

Kindly help.

答案1

得分: 1

这里是您要翻译的部分:

"当数据结构中的同一位置既可以是标量也可以是向量时,情况并不理想;如果可能存在多值情况,那么如果service 始终是列表,构建和后续使用都会更容易。

然而,针对您提出的问题,您可以这样做:

lookup = {}
for item in data:
    key = tuple(item["unit"])
    olditem = lookup.get(key)
    if olditem:
        if isinstance(olditem["service"], str):
            olditem["service"] = [olditem["service"]]
        olditem["service"].append(item["service"])
    else:
        lookup[key] = item
output = list(lookup.values())
print(output)
# => [{'service': ['1', '2'], 'unit': ['A', 'B']}, {'service': '1', 'unit': ['C']}]

需要注意的事项:由于您是根据相同的单元进行分组,应该将单元用作查找键,而不是服务。此外,列表不能用作字典的键,但元组可以。"

英文:

It is not great when the same place in the data structure is either a scalar or a vector; it would be easier to both construct and use later if service was consistently a list if it has a possibility to be multivalued.

However, to answer your question as asked, you can do this:

lookup = {}
for item in data:
    key = tuple(item["unit"])
    olditem = lookup.get(key)
    if olditem:
        if isinstance(olditem["service"], str):
            olditem["service"] = [olditem["service"]]
        olditem["service"].append(item["service"])
    else:
        lookup[key] = item
output = list(lookup.values())
print(output)
# => [{'service': ['1', '2'], 'unit': ['A', 'B']}, {'service': '1', 'unit': ['C']}]

Things to note: since you are grouping by the same unit, you should use the unit as the lookup key, not service. Furthermore, lists cannot be used as keys in a dictionary, but tuples can.

答案2

得分: 0

以下是翻译好的内容:

需要一个临时字典来合并与相关的 'service' 的常见值,类似于这样:

data = [
    {"service": "1", "unit": ["A", "B"]},
    {"service": "2", "unit": ["A", "B"]},
    {"service": "1", "unit": ["C"]}
]

temp = {}

for d in data:
    temp.setdefault(tuple(d['unit']), []).append(d['service'])

output = [{'service': v, 'unit': list(k)} for k, v in temp.items()]

print(output)

输出:

[{'service': ['1', '2'], 'unit': ['A', 'B']}, {'service': ['1'], 'unit': ['C']}]
英文:

You need a temporary dictionary to consolidate the common values with the associated 'service'

Something like this:

data = [
    {"service":"1","unit":["A","B"]},
    {"service":"2","unit":["A","B"]},
    {"service":"1","unit":["C"]}
    ]

temp = {}

for d in data:
    temp.setdefault(tuple(d['unit']), []).append(d['service'])

output = [{'service': v, 'unit': list(k)} for k, v in temp.items()]

print(output)

Output:

[{'service': ['1', '2'], 'unit': ['A', 'B']}, {'service': ['1'], 'unit': ['C']}]

huangapple
  • 本文由 发表于 2023年7月6日 13:37:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定