Need help printing list

只愿长相守 提交于 2021-01-27 06:24:57

问题


I'm working on a todo list in Python and I am currently stuck on printing the todo list.

I have my add code and view code as such:

if sel == '1': #add task        
     name = input("enter task name: ")
     prio = input("enter priority level (High | Medium | Low): ")
     add(todo, name, prio)
     view(task)
elif sel == '3': #print todo list
     view2(task)
     exit

and these are the functions im using:

def add(todo, x, y):
    todo[x] = y

def view(x):
    x.append(dict(todo))

def view2(x):
    print(x)

I'm able to add items to a dictionary print the dictionary the first time i select the option to print list. The second time i print it gives the below output

[{'test 1': 'low'}, {'test 1': 'low', 'test 2 ': 'low'}]

my ultimate goal is to get an output as shown below, but i can't get passed this first wall. Any advice? also, would i need to print a nested dictionary to get a numbered list?

1 - test 1 - low
2 - test 2 - low

Thanks in advance !


回答1:


Assuming view2(x) is the function for printing and x is the dictionary which you have mentioned in the question.

You can do something like this

def view2(x):
    for key, val in x.items():
        print("{0} - {1}".format(key, val))



回答2:


This code will work for any number of todos in the list.

todo_list = [{'test 1': 'low'}, {'test 2': 'low'}]
def show(todo_list):
    for index, todo in enumerate(todo_list, start=1):
        for key in todo.keys(): 
            print(index, key, todo[key])

show(todo_list)


来源:https://stackoverflow.com/questions/63872369/need-help-printing-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!