如何在python中将值附加到字典中的键

时间:2020-03-15 00:46:54

标签: python dictionary

假设我有一个示例字典:

f = {"1", "2", "3", "4", "5", "6", "7", "8"}

如何将值附加到所有值上,使其看起来像:

f = {"1":"one", "2":"two", "3":three", "4":"four", "5":"five", "6","six:, "7":"seven", "8":"eight"}

2 个答案:

答案 0 :(得分:1)

此示例是set而不是dictionary

f = {"1", "2", "3", "4", "5", "6", "7", "8"}

字典需要相应键的值。从技术上讲,您不会将值“附加”到键上,该字保留给其他数据结构,可以在其中插入元素,但是可以为键分配值:

f = dict()
f['1'] = 'one'

您还可以将列表/集合分配给字典中的键,并将附加值分配给这些列表:

z = list()
f = dict()
f['1'] = z
f['1'].append('one')

答案 1 :(得分:0)

要实现您的示例,这应该可以解决问题:

import inflect

f = {"1", "2", "3", "4", "5", "6", "7", "8"}

engine = inflect.engine()
f = {k: engine.number_to_words(int(k)) for k in f}

请注意,字典未排序,因此结果为:

{'4': 'four',
 '6': 'six',
 '8': 'eight',
 '1': 'one',
 '5': 'five',
 '3': 'three',
 '2': 'two',
 '7': 'seven'}