Home > Software design >  Trying to printing the dictionary values by taking a list of strings and given user input
Trying to printing the dictionary values by taking a list of strings and given user input

Time:10-07

I am trying to print the values as a dictionary (like as key and value) with output like {0: 'Rama', 1: 'Sita', 2: 'Ravana'}.

Tried Code:

def details():
  Stu_Rec = {}
  Names = list()
  print("Enter the Id :\n")
  Id = int(input())
  for i in range(0,Id):
    print("\nEnter the Name ")
    Name = input()
    Names.append(Name)
  for i in range(0,Id):
    for x in Names:
       Stu_Rec[i] = x
  return Stu_Rec

if __name__ == "__main__": 
  Details = details()
  print(Details)**

When i am executing the code , the output is mentioned above and below is the snippet

~/Python-3$ python details.py
Enter the Id :

3

Enter the Name 
rama

Enter the Name 
sita

Enter the Name 
Ravana
{0: 'Ravana', 1: 'Ravana', 2: 'Ravana'}**

Suggest what's wrong with the code I'm trying ?

CodePudding user response:

Try this.

def details():
Stu_Rec = {}
Names = list()
print("Enter the Id :\n")
Id = int(input())
for i in range(0,Id):
    print("\nEnter the Name ")
    Name = input()
    Names.append(Name)
for i in range(0,Id):
    Stu_Rec[i] = Names[i]
return Stu_Rec

if __name__ == "__main__": 
    Details = details()
    print(Details)

CodePudding user response:

Explanation:

Your implementation is wrong here for x in Names:, in this loop dict value is updated with the last name of the Names list that's why you got that.

Try this:

def details():
    Stu_Rec = {}
    Names = list()
    print("Enter the Id :\n")
    Id = int(input())
    for i in range(0,Id):
        print("\nEnter the Name ")
        Name = input()
        Names.append(Name)

    for i in range(0,Id):
        Stu_Rec[i] = Names[i]
    return Stu_Rec

if __name__ == "__main__": 
    Details = details()
    print(Details)

Output:

Enter the Id :

3

Enter the Name 
Rama

Enter the Name 
Sita

Enter the Name 
Ravana
{0: 'Rama', 1: 'Sita', 2: 'Ravana'}
  • Related