Home > Net >  Python Create a new list with dictionaries of which one value is of another list only if the value o
Python Create a new list with dictionaries of which one value is of another list only if the value o

Time:06-09

I have a dictionary of income activities and values (yes or no) and a list of button titles. The goal is to create a new list and always append a dictionary in which one value is from the button tiles if the value of an income activity is "yes". However, I do not know how to iterate over the "income activities and values" dictionary and over the titles at the same time to always set the correct title in the new dictionary. This is the code:

income_activities = ['question_fishing','question_livestock','question_firewood','question_crop']
income_activities_values =  [tracker.get_slot("question_fishing"), tracker.get_slot("question_livestock"),  tracker.get_slot("question_firewood"), tracker.get_slot("question_crop")]
dic = dict(zip(income_activities, income_activities_values))

button_titles = ['Fishing', 'Livestock', 'Firewood', 'Crop']

buttons = [] #new list of dictionaries
for key, value in dic.items():
        if value == 'yes':
            buttons.append({"payload":'/affirm', "title": value_of_button_titles})

So for example if the dic looks like this:

{'question_fishing': 'yes', 'question_livestock': 'yes', 'question_firewood': 'no', 'question_crop': 'yes'}

The final button list of dictionaries should look like this:

 buttons=[
        {"payload":'/affirm', "title": "Fishing"},
        {"payload":'/affirm', "title": "Livestock"},
        {"payload":'/affirm', "title": "Crop"}     
    ]

CodePudding user response:

Not sure if I got the question right, but how about:

for button_title, (key, value) in zip(button_titles, dic.items()):
    if value == 'yes':
        buttons.append({"payload":'/affirm', "title": button_title})

CodePudding user response:

You could iterate on an index instead of values:

for i in range(len(dic)):
        if income_activities_values[i] == 'yes':
            buttons.append({"payload":'/affirm', "title": button_titles[i]})
  • Related