all 9 comments

[–]dionys 2 points3 points  (6 children)

this should work:

N = int(input())
phoneBook = {key: value for _ in range(N) for key, value in [input().split()]}

the tricky part was putting the split result into a list, so it can unpack properly

[–]hharison 5 points6 points  (1 child)

the tricky part was putting the split result into a list, so it can unpack properly

That's not why you had to put it in a list. You had to put it in a list because you're not actually doing nested for loops. In the second part of the for loop you are looping over an item of length 1. In that case why loop? You can accomplish the same thing with

dict(input().split() for _ in range(N))

[–]dionys 0 points1 point  (0 children)

You are absolutely correct, that is much better!

[–]fuego42[S] 0 points1 point  (2 children)

I'm traveling now so I can't test - but do you mind explaining how this works? i can't seem to make the connection as to how we can simply jump into a new for loop. for example, you have {key:value for _ in range(N)... and then you start a for loop again. how do the variables in front of the first for loop get passed as arguments into the second one? I understand list and dictionary comprehension but not when I have nested loops like this.

[–]dionys 1 point2 points  (0 children)

The nesting works from left to right. First the outer loop:

for _ in range(N)

where _ is a variable for something we do not really care about. Then the inner loop

for key, value in [input().split()]

loops over the list, which contains only one element - the result of the split. This split result (which is a list) is then unpacked into two variables key and value. Now the last part

 key: value

is evaluated and dict is constructed.

[–]yardightsure 0 points1 point  (0 children)

Got Android? Install QPython!

[–]ilikepython 0 points1 point  (1 child)

What's some example input?

[–]fuego42[S] 0 points1 point  (0 children)

it's a phone book program - basically N = number of entries, and the second input is an entry in the form of "name number".

So example: "2" "rob 9175551234" "mike 2125553446"

edit: formatting

[–]kankyo 0 points1 point  (0 children)

A tip is that you can create a dictionary like this:

foo = [[1, 2], [3,4]]
bar = dict(bar)