简体   繁体   English

打印Python中For Loop的所有字典结果

[英]Printing all dictionary results from For Loop in Python

I am trying to print the results from all 3 names that are input, in a dictionary format. 我试图以字典格式打印输入的所有3个名称的结果。 Current code below only prints out the last name. 下面的当前代码仅打印出姓氏。 The 2 lines commented out (#) are what I was trying to change around to get it to work, clearly not doing it correctly. 注释掉(#)的2行是我试图改变它以使其工作,显然没有正确地做。

def name():
    count = 0
    while (count  < 5):
        d = {}
        qs = dict(Fname='first name', Lname='last name')
        for k,v in qs.items():
            d[k] = input('Please enter your {}: '.format(v))
                #d['first name'].append(v)
                #d['last name'].append(v)
                count += 1
    print(d)

name()

A few things that I'd change: 我要改变的一些事情:

  • append each record ( dictionary ) to a list of entries. 将每条记录( dictionary )附加到条目list中。
  • (optional) Use a for-loop rather than a while as less lines of code. (可选)使用for-loop而不是一段while作为更少的代码行。
  • return the entries list, rather than print it as it is a function so I like to have outputs. 返回entries列表,而不是print它,因为它是一个function所以我喜欢有输出。

So here's the corrected code: 所以这是更正后的代码:

def name():
    entries = []
    for count in range(5):
        d = {}
        qs = dict(Fname='first name', Lname='last name')
        for k, v in qs.items():
            d[k] = input('Please enter your {}: '.format(v))
        entries.append(d)
    return entries

print(name())

For testing purpose, I modified it to just except 2 entries, but we can still see that it works: 出于测试目的,我将其修改为除了2个条目,但我们仍然可以看到它有效:

Please enter your last name: fish
Please enter your first name: bowl
Please enter your last name: cat
Please enter your first name: mat
[{'Lname': 'fish', 'Fname': 'bowl'}, {'Lname': 'cat', 'Fname': 'mat'}]

Hope! 希望! you got it right from Martijin Comments, For reference to other adding this code: 你是从Martijin评论得到的,有关其他添加此代码的参考:

def name():
    count = 0
    listOfDict = [] #creating empty list
    for count in range(3):
        dict = {}
        qs = dict(Fname = 'first name', Lname = 'last name' )
        for k,v in qs.items():
            d[k] = input('please enter your {}: '.format(v))
        listOfDict.append(d) # adding each item to the list.
        count += 1
    print listOfDict

name()

This should work: 这应该工作:

def name():
    count = 0
    while (count  < 5):
        d = {}
        qs = dict(Fname='first name', Lname='last name')
        for k,v in qs.items():
            a = input('Please enter your {}: '.format(v))
            d[v] = a
        count += 1
        print(d['first name'],d['last name'])

name()

You can use defaultdict to automatically create lists to store each entered value. 您可以使用defaultdict自动创建列表来存储每个输入的值。 The main idea is that you want to append each entered value to a collection of some type (eg list). 主要思想是您希望将每个输入的值附加到某种类型的集合(例如列表)。

from collections import defaultdict

number_of_entries = 3
dd = defaultdict(list)
for _ in range(number_of_entries):
    for key in ('first name', 'last_name'):
        dd[key].append(input('please enter you {}: '.format(key)))

>>> print(dict(dd))
{'first name': ['Adam', 'Milton', 'Irving'],
 'last_name': ['Smith', 'Friedman', 'Fisher']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM