使用相同键但值不同的Python字典

时间:2018-08-16 08:22:37

标签: python dictionary

我想从键和值对创建一个字典。问题是我有相同的键但值不同。所以我的目标是创建

menu = [
    {"viewclass": "MDMenuItem",
     "text" : "option1"},
    {"viewclass": "MDMenuItem",
     "text" : "option2"}
]

我尝试使用for循环创建此变量

length = 2
menu = {}

view_class_keys = length * ["viewclass"]
view_class_values = length * ["MDMenuItem"]
text_keys = length * ["text"]
text_values = ["option1", "option2"]

for iterator in range(0, length):
    menu[view_class_keys[iterator]] = view_class_values[iterator]
    menu[text_keys[iterator]] = text_values[iterator]

print([menu])

# Output: [{'viewclass': 'MDMenuItem', 'text': 'option2'}]

我知道问题在于密钥相同,但是我不知道如何解决此问题。

4 个答案:

答案 0 :(得分:2)

您非常亲密。您应该将字典汇总到列表中 在每次迭代上创建新词典时,将其附加到结果列表中:

length = 2
menu_list = []
view_class_keys = length * ["viewclass"]
view_class_values = length * ["MDMenuItem"]
text_keys = length * ["text"]
text_values = ["option1", "option2"]

for iterator in range(0, length):
    menu = {}
    menu[view_class_keys[iterator]] = view_class_values[iterator]
    menu[text_keys[iterator]] = text_values[iterator]
    menu_list.append(menu)

print(menu_list)

编辑: 假设代码中唯一的可变部分是text_values列表, 您的代码可以简化为

menu = [{"viewclass": "MDMenuItem", "text" : option} for option in text_values]

答案 1 :(得分:1)

也许是这样的:

names(listData) <- basename(dirname(fileList))

答案 2 :(得分:0)

OR:

length = 2
text_values = ["option1", "option2"]
print([dict(viewclass="MDMenuItem", text=option) for option in text_values])

答案 3 :(得分:0)

这应该可以解决您的问题:

length = 2
# in your goals, "menu" type is a list
menu = []

view_class_keys = length * ["viewclass"]
view_class_values = length * ["MDMenuItem"]
text_keys = length * ["text"]
text_values = ["option1", "option2"]


for iterator in range(0, length):
    #first time you have to append to the list a new dictionary
    menu.append({view_class_keys[iterator]:view_class_values[iterator]})
    #than you can add a new key value to the dict 
    menu[iterator][text_keys[iterator]] = text_values[iterator]

#I leave the square brackets cause menu is already a list
print(menu)

# Output: [{'viewclass': 'MDMenuItem', 'text': 'option1'}, {'viewclass': 'MDMenuItem', 'text': 'option2'}]

但是,由于您为不同的值使用相同的键,因此dict可能不是您的最佳选择。也许您可以尝试像这样的单个列表:

length = 2
menu = []

view_class_keys = length * ["viewclass"]
view_class_values = length * ["MDMenuItem"]
text_keys = length * ["text"]
text_values = ["option1", "option2"]

for iterator in range(0, length):
    menu.append([view_class_keys[iterator],view_class_values[iterator]])
    menu.append([text_keys[iterator],text_values[iterator]])

print(menu)
# Output: [['viewclass', 'MDMenuItem'], ['text', 'option1'], ['viewclass', 'MDMenuItem'], ['text', 'option2']]