python - 解析字典以具有一对一的键值映射

标签 python algorithm dictionary graph-algorithm

我有一本字典,其键映射到值列表。我正在尝试创建一个函数,该函数输出一个字典,其键仅映射到一个值。在字典中,如果键映射到元素列表,则列表的第一个元素是正确的值,并且应该被持久化,并且列表的其他元素应该映射到字典中的该元素。但是,如果第一个元素之前已链接到另一个值,则它应该链接到该值

示例

输入:
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”应该是持续存在的值(因为它是第一个元素)。但由于“apples”链接到“fruit1”和“fruit2”,因此“fruit2”也应该链接到“fruit1”。

然后,当“grape”映射到“fruit2”时,“grape”应该重新链接到“fruit1”,因为“fruit2”之前链接到“fruit1”。同样,输出中的“mango”映射到“fruit3”,因为“round”之前链接到“fruit3”(对于橙色)

Key 属性:键中不存在字典的任何值

我的代码:

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

有人建议如何获得正确的输出吗?我在代码中维护一个字典,捕获已重新链接的字典的值,因此我始终可以将当前值路由到该字典。虽然,似乎是某个地方的错误

最佳答案

这是我的方法:

q = dict()
for k, values in d.items():
    c = values[0]
    q[k] = q.get(c, c)
    for v in range(1, len(values)):
        q[values[v]] = q.get(c, c)
Output : 
{'apples': 'fruit1',
 'fruit2': 'fruit1',
 'fruit5': 'fruit1',
 'grape': 'fruit1',
 'mango': 'fruit3',
 'orange': 'fruit3',
 'round': 'fruit3'}

我们将其存储在新的字典中,在存储之前,我们不断检查是否有任何链接已存储值,如果是,则我们使用链接值而不是创建新链接,否则我们创建新链接。

关于python - 解析字典以具有一对一的键值映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67402501/

相关文章:

python - 如何使用Robot Framework设置系统属性 "webdriver.gecko.driver"?

c - 查找数组的平均值

algorithm - 动态规划的最大递增子序列

Javascript数组映射函数保留数组先前项目的记录

python - 有没有更好的方法来检查列表的所有条目是否在另一个列表中?

Python:如何在大于 M 个公共(public)列中找到大于 N 行且单元格非零

python - 有没有比转换为字符串更好的方法在 python 中创建字典键?

algorithm - 接近检测的关闭点

C++ map 输出格式化垃圾

python - 为什么比较空值不起作用?