mo1010
mo1010

Reputation: 185

python dictionaries. Two strings as key

I'm new to python and trying to figure out how to take 3 strings separated by space as input and then the first two will be the key of the desired dictionary and the 3rd string would be the key:

example:

 John Smith 1234
 Mike Tyson 5678

dictonary should be like this:

{'John Smith': '1234', 'Mike Tyson': '5678'}

if it was just two strings that's pretty straightforward and i get the right answer:

   count=int(input())
   d=dict(input().split() for x in range(count))
   print(d)

Upvotes: 0

Views: 645

Answers (5)

krishna
krishna

Reputation: 1029

You can use rsplit last item.


count = int(input("How many times data you want to enter: "))
data_list = [input("Please enter the {} data: ".format(x + 1)) for x in range(count)]

output_dict = dict(item.rsplit(' ', 1) for item in data_list)
print("Output:\n", output_dict)
>>

Output:

How many times data you want to enter: 2
Please enter the 1 data: John Smith 1234
Please enter the 2 data: Mike Tyson 5678
Output:
 {'John Smith': '1234', 'Mike Tyson': '5678'}

Upvotes: 0

Multivac
Multivac

Reputation: 815

Assuming the string inputs is fixed to be = 3 and that you are going to receive the strings into a list:

from functools import reduce

S = ["John Smith 1234", "Mike Tyson 5678"]

reduce(lambda x,y: dict(x, **y), [dict([[" ".join(s.split()[:2]),s.split()[-1]]]) for s in S])

>> {'John Smith': '1234', 'Mike Tyson': '5678'}

Upvotes: 0

Wups
Wups

Reputation: 2569

# generator to yield input until an empty string is entered
def get_input():
    s = input()
    while s:
        yield s
        s = input()

# get input from the generator, split at the last " " and make a dict from it
d = dict(line.rsplit(maxsplit=1) for line in get_input())

A function to chose the number of loops at the beginning:

def get_input():
    count = int(input("how many entries: "))
    for _ in range(count):
        yield input()

Upvotes: 0

InhirCode
InhirCode

Reputation: 348

could use str.rpartition(). This returns a tuple of the first two strings, the space, and the final string. (Python 3.10)

s = input()
key, space, final = s.rpartition(' ')
d = {key:final}

Upvotes: -1

user7864386
user7864386

Reputation:

You can use rsplit with maxsplit=1; that way, you only split once from the right:

lst = ['John Smith 1234', 'Mike Tyson 5678']
d = {}
for string in lst:
    s = string.rsplit(maxsplit=1)
    d[s[0]] = s[1]

Output:

{'John Smith': '1234', 'Mike Tyson': '5678'}

Upvotes: 10

Related Questions