python - 解析字典以具有一对一的键值映射
问题描述
我有一本字典,它的键映射到一个值列表。我正在尝试创建一个函数,该函数输出一个其键仅映射到一个值的字典。在字典中,如果键映射到元素列表,则列表的第一个元素是正确的值,并且应该被持久化,并且列表的其他元素应该映射到字典中的这个元素。但是,如果第一个元素之前链接到另一个值,它应该链接到那个
例子
输入:d = {
'apples': ['fruit1', 'fruit2'],
'orange': ['fruit3', 'round'],
'grape':['fruit2', 'fruit5'],
'mango': ['round']
}
预期输出:
o = {'apples': 'fruit1', # since fruit1 was the first element
'fruit2': 'fruit1', # fruit2 should link to the first element (fruit1)
'orange': 'fruit3', # first element persisted
'round': 'fruit3', # second element, round, links to the first, fruit3
'grape': 'fruit1', # should keep first element fruit2, but since fruit2 linked to fruit1 earlier, link to fruit1
'fruit5': 'fruit1', # since fruit2 links to fruit1
'mango': 'fruit3' # since round links to fruit 3
}
在此示例中,“apples”链接到输入中的fruit1 和fruit2。“fruit1”应该是持续存在的值(bc 它的第一个元素)。但是由于“apples”链接到“fruit1”和“fruit2”,“fruit2”也应该链接到“fruit1”。
然后,当“grape”映射到“fruit2”时,“grape”应该重新链接到“fruit1”,因为“fruit2”更早地链接到了“fruit1”。同样,输出中的“mango”映射到“fruit3”,因为“round”之前链接到“fruit3”(橙色)
键属性:键中不存在字典的任何值
我的代码:
new_d = {}
relinked_items = {}
for key, values in d.items():
if len(values) == 1:
value = values[0]
if key not in new_d:
# if value has been relinked before, link to that
if value in relinked_items:
new_d[key] = relinked_items[value]
# hasnt been relinked
else:
new_d[key] = value
continue
target_value = values[0]
# link key to target value
new_d[key] = target_value
for value in values[1:]:
if target_value in relinked_items:
new_d[value] = relinked_items[target_value]
# hasnt been relinked
else:
new_d[value] = target_value
我的输出
{'apples': 'fruit1', # correct
'fruit2': 'fruit1', # correct
'fruit5': 'fruit2', # wrong. fruit2 maps to fruit1
'grape': 'fruit2', # wrong fruit2 maps to fruit1
'mango': 'round', # wrong. round maps to fruit3
'orange': 'fruit3', # correct
'round': 'fruit3'} # correct
有人就如何获得正确的输出提出建议吗?我在我的代码中维护一个 dict 捕获已重新链接的 dict 的值,因此我始终可以将当前值路由到该值。虽然,似乎是某个地方的错误
解决方案
所以我想这不是一个灵活的解决方案,但它解决了你的问题:
d = {
'apples': ['fruit1', 'fruit2'],
'orange': ['fruit3', 'round'],
'grape':['fruit2', 'fruit5'],
'mango': ['round']
}
new = {}
# invraping dict
for k in d:
v = d[k]
for i in range(1, len(v)):
new[v[i]] = v[0]
new[k] = v[0]
# appliing your special rules
for k in new:
v = new[k]
if v in new:
new[k] = new[v]
print(new)
推荐阅读
- winapi - 我如何在 C++ 中的 32 位 HBITMAP 上使用 Fillrect 或 DrawText
- reactjs - 使用 babel7 时,forwardRef 不是 buildReactRelayContainer 的函数
- assembly - MIPS 不能在程序中改变值
- python - 从另一个 Python 文件执行函数时遇到问题
- database - 我需要什么类型的数据库?
- java - Java 与 Swift 中的常量类型
- python - ModuleNotFoundError:没有名为“speech_recognition”的模块
- python - 使用 Dask 读取多个文件
- c++ - C++ 打印包含数据结构的数组
- c# - Xamarin Forms - 如何在 ListView 中显示 JSON 数组?