我有一个唯一键字典,其中一些键共享相同的值。
例如:
D = {'ida':{'key':'1'},'idb':{'key':'2'},'idc':{'key':'3'},'idd':{'key':'3'},'ide':{'key':'4'},'idf':{'key':'4'},'idg':{'key':'4'}}
我想要一个与其他键共享相同值的键列表。
在这种情况下,它将是
l = ['idc','idd','ide','idf','idg']
但是,我想从共享相同值的所有键集中排除一个键。
例如,我想拥有密钥
l = ['idd','idf','idg']
排除'idc'和'ide'
或者可能是
l = ['idc','ide','idf']
排除'idd'和'idg'。
答案 0 :(得分:1)
如果值出现多次,则list comp将添加该键。
dup_keys = [k for k in D if sum(D[k] in x for x in D.iteritems()) > 1 ]
['idf', 'idg', 'idd', 'ide', 'idc']
dup_keys[1:]
['idg', 'idd', 'ide', 'idc']
dup_keys[1:-1]
['idg', 'idd', 'ide']
if sum(D[k] in x for x in D.iteritems()) > 1
检查值> 1
次。
要忽略某些键添加一些and
条件,我不确定您想要忽略哪些键。
答案 1 :(得分:-3)
# aDictionary = { <aKey>: <aValue>, ... } python dictionary constructor
aDictionary = { 'ida': '1', \
'idb': '2', \
'idc': '3', \
'idd': '3', \
'ide': '4', \
'idf': '4', \
'idg': '4' \
}
# the OP used aDictionaryOfDictionaries construction instead.
# aDictOfDICTs = {'ida':{'key':'1'},'idb':{'key':'2'}, ... }
# The algorithmisation of the processing task is different.
# for aDictionary, a inverseDictionary may be assembled
# to hold for each <aValue>,
# a referring <aKey>, incl. those, where are more than one primary <aKey>-s,
# ( stored asListOfPrimaryKEYs or aSetOfPrimaryKEYs ), which len() is easy to test
公平&amp;适当的anInverseDICTIONARY构造的强大解决方案 可以在&#34;快速功能解决方案中找到非双射地图(值不唯一):&#34;在&gt;&gt;&gt; https://stackoverflow.com/a/22235665/3666197
请注意,并非所有帖子都能在那里产生强大的解决方案。
<强>最后强>
>>> aListOfDUP_KEYs = [ anInvDictKEY for anInvDictKEY in anInverseDICTIONARY.keys() if ( len( anInverseDICTIONARY[anInvDictKEY] ) > 1 ) ]
[ 3, 4 ]
''' as anInverseDICTIONARY = { 1: set( [ 'ida' ] ),
2: set( [ 'idb' ] ),
3: set( [ 'idd', 'idc' ] ),
4: set( [ 'idg', 'idf', 'ide' ] )
}
'''
通过DUP_KEY从 anInverseDICTIONARY 中移除任何一个DUP-e,或通过列表理解从原始的 aDictionary
移除
>>> [ aDictionary.pop( anInverseDICTIONARY[aDUP_KEY].pop() ) for aDUP_KEY in aListOfDUP_KEYs ]
[ 'idd', 'idf' ]