Home > Software engineering >  python dictionaries. Two strings as key
python dictionaries. Two strings as key

Time:01-14

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)

CodePudding user response:

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'}

CodePudding user response:

# 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()

CodePudding user response:

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}

CodePudding user response:

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'}
  •  Tags:  
  • Related