Mohammad Reza Aram
Mohammad Reza Aram

Reputation: 129

problem in dictionary items ,they are not saved

in this code i dont know why dict is not work

x=input()  # receive number that indicate how many input we have
c=0
z=[]
while int(x)!=c:
    z.append(input().split('.'))     # this inputs are string ,its divide to three part with '.'like   ac.milan.1999
    c+=1
z1=[]
z3=[]
for i in z :   #i want make dictionary with z1 as keys and z3 as values
    z2=[]
    z1.append(i[0].lower())     #part one of string goes to z1
    z2.append(i[1].lower().capitalize())    #part 2 and 3 goes to z3 
    z2.append(i[2].lower())
    z3.append(z2)
d = {}

d=dict(zip(z1,z3))
print(d)

when i give 2 in first input and two string in next inputs it is work but when i give it 4 its just print the last two items for example

4
male.max.python
female.kate.java
male.alex.javascript
female.maria.python
{'male': ['Alex', 'javascript'], 'female': ['Maria', 'python']}

thanks in advance if its unclearly let me know. i know its primary question but i am beginner and want to learn

Upvotes: 1

Views: 115

Answers (1)

The lists are being replaced in your for when you create z2 = [] inside the loop and access it outside. You can't do that.

Try this solution:

x=input()  # receive number that indicate how many input we have
c=0
z=[]

while int(x)!=c:
    z.append(input().split('.'))     # this inputs are string ,its divide to three part with '.'like   ac.milan.1999
    c+=1

z1=[]
z3=[]
d = {}
for i in z :   #i want make dictionary with z1 as keys and z3 as values
    i[1] = i[1].lower().capitalize()
    if i[0].lower() not in d:
        d[i[0].lower()] = []
    
    d[i[0].lower()].append(i[1:])
    
print(d)

It will return:

4
male.max.python
female.kate.java
male.alex.javascript
female.maria.python
{'male': [['Max', 'python'], ['Alex', 'javascript']], 'female': [['Kate', 'java'], ['Maria', 'python']]}

Or other option with less code

x=input()  # receive number that indicate how many input we have
c=0
d = {}
while int(x)!=c:
    c+=1
    z = input().split('.')
    z[1] = z[1].lower().capitalize()
    if z[0].lower() not in d:
        d[z[0].lower()] = []

    d[z[0].lower()].append(z[1:])

print(d)

Upvotes: 1

Related Questions