[英]Get key by more than one value in dictionary?
Maybe the dict
is not intended to be used in this way, but I need to add more than one value to the same key.也许
dict
不打算以这种方式使用,但我需要向同一个键添加多个值。 My intension is to use a kind of transitory property.我的意图是使用一种短暂的财产。 If my dict is
A:B
and B:C
, than I want to have the dict A:[B,C]
.如果我的 dict 是
A:B
和B:C
,那么我想要的 dict A:[B,C]
。
Let's make an example in order to explain better what I'd like to do:让我们举一个例子来更好地解释我想做的事情:
numDict={'60':['4869'], '4869':['629'], '13':['2']}
I want it to return:我希望它返回:
{'60':['4869','629'], '13':['2']}
For just two elements, it is possible to use something like this:对于只有两个元素,可以使用这样的东西:
result={}
for key in numDict.keys():
if [key] in numDict.values():
result[list(numDict.keys())[list(numDict.values()).index([key])]]=[key]+numDict[key]
But what about if I have more elements?但是如果我有更多的元素呢? For example:
例如:
numDict={'60':['4869'], '4869':['629'], '13':['2'], '629':['427'}
What can I do in order to get returned {'60':[4869,629,427'], '13':['2']}
?我该怎么做才能得到返回
{'60':[4869,629,427'], '13':['2']}
?
I have written a code for it.我已经为它写了一个代码。 See if it helps.
看看它是否有帮助。
What I have done is to go on diving in till i can go (hope you understand this statement) and mark them as visited as they will no longer be required.我所做的是继续潜入直到我可以去(希望你理解这个声明)并将它们标记为已访问,因为它们将不再需要。 At the end I filter out the root keys.
最后我过滤掉了根键。
numDict={'60':['4869'], '4869':['629'], '13':['2'], '629':['427']}
l = list(numDict) # list of keys
l1 = {i:-1 for i in numDict} # to track visited keys (initialized to -1 initially)
for i in numDict:
# if key is root and diving in is possible
if l1[i] == -1 and numDict[i][0] in l:
t = numDict[i][0]
while(t in l): # dive deeper and deeper
numDict[i].extend(numDict[t]) # update the value of key
l1[t] = 1 # mark as visited
t = numDict[t][0]
# filter the root keys
answer = {i:numDict[i] for i in numDict if l1[i] == -1}
print(answer)
Output:输出:
{'60': ['4869', '629', '427'], '13': ['2']}
def unchain(d):
#assemble a collection of keys that are not also values. These will be the keys of the final dict.
top_level_keys = set(d.keys()) - set(d.values())
result = {}
for k in top_level_keys:
chain = []
#follow the reference chain as far as necessary.
value = d[k]
while True:
if value in chain: raise Exception("Referential loop detected: {} encountered twice".format(value))
chain.append(value)
if value not in d: break
value = d[value]
result[k] = chain
return result
numDict={'60':'4869', '4869':'629', '13':'2', '629':'427'}
print(unchain(numDict))
Result:结果:
{'60': ['4869', '629', '427'], '13': ['2']}
You might notice that I changed the layout of numDict
since it's easier to process if the values aren't one-element lists.您可能会注意到我更改了
numDict
的布局,因为如果值不是单元素列表, numDict
容易处理。 But if you're dead set on keeping it that way, you can just add d = {k:v[0] for k,v in d.items()}
to the top of unchain
, to convert from one to the other.但如果你是在保持这种方式死心塌地,你可以添加
d = {k:v[0] for k,v in d.items()}
到顶部unchain
,从一个转换到另一个.
You can build your own structure, consisting of a reverse mapping of (values, key)
, and a dictionary of (key, [values])
.您可以构建自己的结构,由
(values, key)
的反向映射和(key, [values])
的字典组成。 Adding a key, value
pair consists of following a chain of existing entries via the reverse mapping, until it finds the correct location;添加
key, value
对包括通过反向映射跟踪现有条目链,直到找到正确的位置; in case it does not exist, it introduces a new key entry:如果它不存在,它会引入一个新的关键条目:
class Groupir:
def __init__(self):
self.mapping = {}
self.reverse_mapping = {}
def add_key_value(self, k, v):
self.reverse_mapping[v] = k
val = v
key = k
while True:
try:
self.reverse_mapping[val]
key = val
val = self.reverse_mapping[val]
except KeyError:
try:
self.mapping[val].append(v)
except KeyError:
self.mapping[val] = [v]
break
with this test client:使用此测试客户端:
groupir = Groupir()
groupir.add_key_value(60, 4869)
print(groupir.mapping)
groupir.add_key_value(4869, 629)
print(groupir.mapping)
groupir.add_key_value(13, 2)
print(groupir.mapping)
groupir.add_key_value(629, 427)
print(groupir.mapping)
{60: [4869]}
{60: [4869, 629]}
{60: [4869, 629], 13: [2]}
{60: [4869, 629, 427], 13: [2]}
Cycles as mentioned in comments.评论中提到的周期。
Non unique keys非唯一键
Non unique values非唯一值
Probably some corner cases to take care of.可能需要处理一些极端情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.