将字典解析为具有onetoone键值映射

2024-09-26 22:54:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

示例

输入:
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
     }

在本例中,“苹果”链接到输入中的水果1和水果2。“fruit1”应该是持续存在的值(bc是第一个元素)。但既然“苹果”链接到“水果1”和“水果2”,那么“水果2”也应该链接到“水果1”

后来,当“葡萄”映射到“水果2”时,“葡萄”应该重新链接到“水果1”,因为“水果2”在前面链接到“水果1”。同样,输出中的“芒果”映射为“水果3”,因为“圆形”之前与“水果3”关联(对于橙色)

键属性:键中不存在dict的任何值

我的代码:

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的值,因此我始终可以将当前值路由到该dict。虽然,似乎是一个错误的地方


Tags: tokey元素targetnewvalue链接items
2条回答

因此,我想这不是一个灵活的解决方案,但它解决了您的问题:

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)

我的做法如下:

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'}

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

相关问题 更多 >

    热门问题