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. 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.

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()

4 answers

  • answered 2018-01-11 20:38 Joe Iddon

    A few things that I'd change:

    • append each record (dictionary) to a list of entries.
    • (optional) Use a for-loop rather than a while as less lines of code.
    • return the entries list, rather than print it as it is a function so I like to have outputs.

    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:

    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'}]
    

  • answered 2018-01-11 20:42 PAC

    Hope! you got it right from Martijin Comments, For reference to other adding this code:

    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()
    

  • answered 2018-01-11 20:42 JimmyCarlos

    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()
    

  • answered 2018-01-12 03:52 Alexander

    You can use defaultdict to automatically create lists to store each entered value. The main idea is that you want to append each entered value to a collection of some type (e.g. 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']}