Im new to python i have problems with understanding Dictionaries in python especially how to get them as input from user Can smn explain it to me as an example on 1 task
1 line is number of records then Actor name and movies they played seperated by comma
output must be movie name:actor name,actor name
I dont undrestand what is key and what is value How should i convert this input lines as dictionary ?
CodePudding user response:
d = {} # initialize empty dictionary
n = int(input()). # get number of input lines
for _ in range(n):
actor, *films = input().split(", ") # get actor and films
for film in films: # add actor to each film in dictionary
d[film] = d.get(film, []) [actor]
for film, actors in d.items(): # iterate the dictionary
print(f"{film}: {', '.join(actors)}") # print the data using join function to add "," character between films
If you need to sort keys and values of them add this code:
for key, value in sorted(d.items(), key=lambda x: x[0]):
d[key] = sorted(value)
CodePudding user response:
initially, you just create an empty dictionary in python. Then input a number to loop a number of times you want to take input. Then put a for loop and input key and value and store them in the dictionary as dict[key]=value.
Here is the code sample in python
dict={}
n=int(input())
for i in range(n):
key=input()
value=intput()
dict[key]=value