[英]Remove the key value pairs based on value
a:{
b:{cd:"abc",
de:"rty"
},
c:{cd:"abc",
de:"uuy"
},
d:{cd:"ap",
de:"uy"
}
}
I want to print values of cd and de from this dictionary and if the value of cd is same then I only want to print once.我想从此字典中打印 cd 和 de 的值,如果 cd 的值相同,那么我只想打印一次。 Expected output: b abc rty d ap uy
预期 output:b abc rty d ap uy
How can I check if the value of cd is repeated or not?如何检查 cd 的值是否重复?
Edit:编辑:
hash_set=set()
hash_item=v1.get('query_hash',{}).get('sha256', "")
if hash_item in hash_set:
break
else:
hash_set.add(hash_item)
This is not working这不起作用
How can I check if the value of cd is repeated or not?
如何检查 cd 的值是否重复?
If you are iterating over stuff and you don't want to process duplicates keep a container of things you have already seen and skip items if they have been seen.如果您正在迭代内容并且您不想处理重复项,请保留一个包含您已经看过的内容的容器,如果已经看过则跳过它们。
sets
are excellent containers for membership testing as the look-up is O(1) and sets don't allow duplicates. sets
是成员测试的优秀容器,因为查找是 O(1) 并且集合不允许重复。
Here is a toy example.这是一个玩具示例。
stuff = 'anjdusttnnssajd'
seen = set()
for thing in stuff:
if thing in seen:
continue
print(thing.upper()) # process thing
seen.add(thing)
Or you could just make a set of the things to process then process the things in the set.或者您可以只制作一组要处理的事物,然后处理该集合中的事物。
stuff = set(stuff)
for thing in stuff:
print(thing.upper())
Using your criteria.使用您的标准。
d = {'a':{'b':{'cd':"abc",'de':"rty"},
'c':{'cd':"abc",'de':"uuy"},
'd':{'cd':"ap",'de':"uy"}}}
seen = set()
for key,thing in d['a'].items():
cd,de = thing['cd'],thing['de']
if cd in seen:
continue
else:
print(key, cd, de)
seen.add(cd)
This code should help, I formated your JSON a little bit for it to be a valid python string but you should be able to modify it as you wish这段代码应该有帮助,我将您的 JSON 格式化为一个有效的 python 字符串,但您应该可以根据需要修改它
def getKeys(dict):
return [*dict]
a = {
'b':{'cd':"abc",
'de':"rty"
},
'c':{'cd':"abc",
'de':"uuy"
},
'd':{'cd':"ap",
'de':"uy"
}
}
cd_list = []
keys = getKeys(a)
for key in keys:
found = False
for checked in cd_list:
if a[key]['cd']==checked:
found = True
break
if not found:
print( f'{key} : {a[key]["cd"]} {a[key]["de"]}')
cd_list.append(a[key]['cd'])
you can try this你可以试试这个
dict={'a':{
'b':{'cd':"abc",
'de':"rty"
},
'c':{'cd':"abc",
'de':"uuy"
},
'd':{'cd':"ap",
'de':"uy"
}
}}
count=0
for key,item in dict.items():
for key,i in item.items():
if item['b']['cd']==i['cd']:
count=count+1
lis=i['cd']
else:
print(i['cd'])
if(count>1):
print(lis)
here is your code这是你的代码
data = {"a":{"b":{"cd":"abc","de":"rty"},"c":{"cd":"abc","de":"uuy"},"d":{"cd":"ap","de":"uy"}}}
output = set()
for key,val in data.items():
for key1,val1 in val.items():
for key2, val2 in val1.items():
if val2 not in output:
output.add(key1)
output.add(val2)
else:
break
print(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.