如何使一个键的值的dic唯一?



我有一个dic列表。value包含一些结果。我想让它们独一无二。(有些是重复的)

dic[0]示例:

{'key': 'art director',
'Results': [{'actor': 1},
{'art director': 4},
{'creative designer': 2},
{'art director': 4},
{'creative designer': 2},
{'digital designer': 1},
{'graphic designer': 1},
{'communications consultant': 1},
{'designer': 1},
{'art director': 4},
{'art director': 4}]}

输出:

{'key': 'art director',
'Results': [{'actor': 1},
{'art director': 4},
{'creative designer': 2},
{'digital designer': 1},
{'graphic designer': 1},
{'communications consultant': 1},
{'designer': 1},
]}

我想使用循环并使用以下if条件:

if dic[i]['Results'][k]==dic[i]['Results'][j]

,但它是不有效的。因为有3个指标。有更好的办法吗?

您可以为您的"Results"值使用字典,而不是一个单键字典列表。所以如下:

{
'key': 'art director',
'Results': [
{'actor': 1},
{'art director': 4},
{'creative designer': 2},
{'art director': 4},
{'creative designer': 2},
{'digital designer': 1},
{'graphic designer': 1},
{'communications consultant': 1},
{'designer': 1},
{'art director': 4},
{'art director': 4}
]
}

import pprint
pprint.pprint({
'key': 'art director',
'Results': {
'actor': 1,
'art director': 4,
'creative designer': 2,
'art director': 4,
'creative designer': 2,
'digital designer': 1,
'graphic designer': 1,
'communications consultant': 1,
'designer': 1,
'art director': 4,
'art director': 4
}
})

由于字典每个键只能有一个值,这将在您构建Results字典时自动处理重复数据删除。

您可以使用这一行,以便获取整个列表(键'Result'的值)并检查重复,然后如果它已经在您的键中,则相应地更改它。

d['Results'] = [dict(t) for t in {tuple(d.items()) for d in d['Results']}]

我有两个解决方案。

解决方案1

第一个将完全输出您所设置的内容:

res = []   # represents the final results list
aux = {}   # used to check if the key is already in 'Results': []
for i in dic:
for r in i['Results']:
for k,v in r.items():
if k not in aux.keys():
aux[k] = v
res.append({k:v})
i['Results'] = res
print(dic)

解决方案2

第二个命令将把dic[I]中的'Results'值转换成一个字典,而不是一个字典列表:

res = {}
for i in dic:
for r in i['Results']:
for k,v in r.items():
res[k] = v
i['Results'] = res
print(dic)

以你的输入为例:


输出:
[{'Results': {'actor': 1,
'art director': 4,
'communications consultant': 1,
'creative designer': 2,
'designer': 1,
'digital designer': 1,
'graphic designer': 1},
'key': 'art director'}]

样本dic:

dic = [{'key': 'art director',
'Results': [{'actor': 1},
{'art director': 4},
{'creative designer': 2},
{'art director': 4},
{'creative designer': 2},
{'digital designer': 1},
{'graphic designer': 1},
{'communications consultant': 1},
{'designer': 1},
{'art director': 4},
{'art director': 4}]}]

相关内容

  • 没有找到相关文章

最新更新