d = {
0:{1,2,3},
1:{567},
2:{2,3,5,8},
3:{4,5,7,9},
4:{6,7,8}
}
我想将第一个k-v对的值与下一个k-v对的键进行比较。
示例:
检查1
中是否存在{1,2,3}
或2
中是否存在{567}
如果确实存在,那么我想删除值中存在的k。
输出应如下所示:
d = {
0:{1,2,3},
2:{2,3,5,8}
}
我尝试使用具有各种排列和组合的字典迭代器,但没有结果。达到结果的最佳方法是什么?
答案 0 :(得分:0)
Python字典未排序,因此我不确定您在这里真的可以说“上一个”的“下一个”。使用pandas
系列更合适。
但是,您仍然可以遍历键并将其定义为订单。
previous = {}
dict_items = list(d.items())
for k,v in dict_items:
if k in previous:
del d[k]
previous = v
编辑:确保键的顺序正确,用以下方法更改dict_items
:
dict_items = sorted(d.items(),key=lambda x:x[0])
会做
答案 1 :(得分:0)
根据示例和要求进行的猜测,您使用的是Python 3.6+,字典将保留插入顺序。您可以这样做:
In [57]: d = {
...: 0:{1,2,3},
...: 1:{567},
...: 2:{2,3,5,8},
...: 3:{4,5,7,9},
...: 4:{6,7,8}
...: }
# Get an iterator from dict.keys
In [58]: keys_iter = iter(d.keys())
# Get the first key
In [59]: first_key = next(keys_iter)
# Populate output dict with first key-value
In [60]: out = {first_key: d[first_key]}
# Populate out dict with key-values based on condition by
# looping over the `zip`-ed key iterator and dict values
In [61]: out.update({k: d[k] for k, v in zip(keys_iter, d.values())
if k not in v})
In [62]: out
Out[62]: {0: {1, 2, 3}, 2: {2, 3, 5, 8}}
答案 2 :(得分:0)
我花了一段时间才弄清楚你想要什么。在下面,我重新措辞了您的示例:
EXAMPLE:
Suppose the input dictionary is as follows:
0:{1,2,3},
1:{567},
2:{2,3,5,8},
3:{4,5,7,9},
4:{6,7,8}
We have...
key of 0:{1,2,3} is 0
value of 0:{1,2,3} is {1,2,3}
key of 2:{2,3,5,8} is 2
value of 2:{2,3,5,8} is {2,3,5,8}
We execute code similar to the following:
if key of 1:{567} in value of 0:{1,2,3}:
# if 1 in {1,2,3}:
delete 1:{567}
if key of 2:{2,3,5,8} in value of 1:{567}:
# if 2 in {567}:
delete 2:{2,3,5,8}
and so on...
"""
以下代码可以实现您的目标:
def cleanup_dict(in_dict):
# sort the dictionary keys
keys = sorted(indict.keys())
# keys_to_delete will tell us whether to delete
# an entry or not
keys_to_delete = list()
try:
while True:
prv_key = next(keys)
nxt_key = next(keys)
prv_val = in_dict[prv_key]
if (nxt_key in prv_val):
keys_to_delete.append(nxt_key)
except StopIteration:
pass
for key in keys_to_delete:
del in_dict[key]
return