合并Dict的Python列表';s(可选)基于属性列表值

合并Dict的Python列表';s(可选)基于属性列表值,python,Python,我正在努力想出一些代码来完成以下所有工作,我想知道是否有人对python有更多的了解可以提供帮助:) 它应当: 从输入的列表中删除重复项-将“account”属性合并到“accounts”列表中-但前提是所有其他属性都相同 如果与“account”不同,则将其放在列表中自己的属性中 作为示例输入和输出可能更好: 输入=[ { “名称”:“核心”, “账户”:“富吧”, “选择”:{ “foo”:“bar” }, }, { “名称”:“核心”, “帐户”:“zed bar”, “选择”:{ “

我正在努力想出一些代码来完成以下所有工作,我想知道是否有人对python有更多的了解可以提供帮助:)

它应当:

  • 从输入的列表中删除重复项-将“account”属性合并到“accounts”列表中-但前提是所有其他属性都相同
  • 如果与“account”不同,则将其放在列表中自己的属性中
作为示例输入和输出可能更好:

输入=[
{
“名称”:“核心”,
“账户”:“富吧”,
“选择”:{
“foo”:“bar”
},
},
{
“名称”:“核心”,
“帐户”:“zed bar”,
“选择”:{
“foo”:“bar”
},
},
{
“名称”:“核心”,
“帐户”:“tup bar”,
“选择”:{
“foo”:“zed”
},
},
]
注意:第三个属性“options>foo”与其他两个属性有何不同

输出=[
{
“名称”:“核心”,
“账户”:[
“富吧”,
“黄色酒吧”
],
“选择”:{
“foo”:“bar”
},
},
{
“名称”:“核心”,
“账户”:[
“tup bar”
],
“选择”:{
“foo”:“zed”
},
},
]
注意它是如何组合前两个元素的——因为名称和选项是相同的。但不合并第三个元素,因为其选项不同

感谢您的帮助,在过去的两天里,我一直在绞尽脑汁尝试各种组合。

基于您的输入

i = 0
j = 0
while i<len(data):
    d1 = data[i]
    while j<len(data):
        if j>i:
            d2 = data[j]
            if d1["name"] == d2["name"] and d1["options"] == d2["options"]:
                if d1["account"]:
                    d1["account"] = [d1["account"]]
                else:
                    d1["account"] = []
                if d2["account"]:
                    d1["account"].append(d2["account"])
                del data[j]
        j+=1
    i +=1

下面是我尝试使用的
pandas
duplicated
assert\u series\u equal

将熊猫作为pd导入
从pandas.testing导入断言_series_equal
输入1=[
{
“名称”:“核心”,
“账户”:“富吧”,
“选择”:{
“foo”:“bar”
},
},
{
“名称”:“核心”,
“帐户”:“zed bar”,
“选择”:{
“foo”:“bar”
},
},
{
“名称”:“核心”,
“帐户”:“tup bar”,
“选择”:{
“foo”:“zed”
},
},
]
df_input1=pd.DataFrame(input1)
df_input1.options=df_input1.options.astype(str)
var_to_append='账户'
vars_to_check=['name','options']
idx\u duplicated=df\u input1.duplicated(子集=vars\u to\u检查)
df_new=df_input1[~idx_duplicated]
df_dup=df_输入1[idx_重复]
df_new[var_to_append]=df_new[var_to_append]。应用(lambda x:[x])
对于df_dup.index中的i:
行重复=方向重复位置[i]
对于df_new.index中的j:
行_new=df_new.loc[j]
尝试:
断言系列相等(行重复[vars\u to\u check],
行新[变量到检查],
检查(名称=假)
df_new.loc[j,var_to_append]+=[row_dup[var_to_append]]
打印('added',row_dup[var_to_append],'to',row_new[var_to_append])
除:
通过
[df_new.to_dict(orient='records')]

使用两个列表按相同索引保留引用

值=[]
账户=[]
对于输入列表中的i:
键=(i['name'],i['options'])
如果输入值:
索引=值。索引(键)
帐户[索引]。追加(i[“帐户”])
其他:
values.append(键)
account.append([i['account']]))
结果=[{'name':名称,'accounts':帐户,'options':options}
对于(名称、选项),zip中的帐户(值、帐户)]

根据您的输入,您可以尝试以下方法:

# Merge entries with the same options.
merged = [{
    "name": d['name'],
    "accounts": list(d2['account'] for d2 in input if d['options'] == d2['options']),
    "options": d['options'],
} for d in input]

# Remove duplicate entries from the output.
output = []
for d in merged:
    if d not in output:
        # If the list contains one element, then replace the list with it.
        if len(d['accounts']) == 1:
            d['accounts'] = d['accounts'][0]
        output.append(d)

print(output)
输出:

[{'name': 'core',
  'account': ['foo-bar', 'zed-bar'],
  'options': {'foo': 'bar'}},
 {'name': 'core', 'account': 'tup-bar', 'options': {'foo': 'zed'}}]
[{'name': 'core', 'accounts': ['foo-bar', 'zed-bar'], 'options': {'foo': 'bar'}}, 
{'name': 'core', 'accounts': 'tup-bar', 'options': {'foo': 'zed'}}]

我不确定是否有办法绕过嵌套的ifs,并在为您正在寻找的名称/选项对构建它时搜索
output
。您可以创建一个
帐户
类,该类具有某些需要的属性,以便于搜索。