简体   繁体   中英

Lists and dictionary conversion in python

So in the following program I have comes up with something that isn't working the way I want, and I need help figuring this out.

The first input takes a string

"Joe,123-5432 Linda,983-4123 Frank,867-5309" 

It first replaces commas with white space, and converts it into list.

['Joe', '123-5432', 'Linda', '983-4123', 'Frank', '867-5309']

However, I want to convert this list into a dictionary using the first entry as the key, and the second entry as the value. So it would look like this:

{'Joe':'123-5432', 'Linda':'983-4123', 'Frank':'867-5309'}

This is where I find my problem (within the function). When I call it into the function it broke it up by individual characters, rather than seeing the .split s as a whole string, which looks like this...

{'J': 'o', 'e': ' ', '1': '2', '3': ' ', '5': '3', ' ': '9', 'i': 'n', 'd': 'a', '8': '6', '-': '4', 'F': 'r', 'a': 'n', 'k': ' ', '7': '-', '0': '9'}

Which ya know is funny, but not my target here.

Later in the program, when Ecall gets an input, it cross references the list and pulls the phone number from the dictionary. Can you help me build a better comprehension for Pdict in the function that does this and not whatever I did?

def Convert(FormatInput):
    Pdict = {FormatInput[i]: FormatInput[i + 1] for i in range(0, len(FormatInput), 2)}
    return Pdict

user_input = input()
FormatInput=user_input.replace(",", " ")
Pdict=Convert(FormatInput)

Ecall = (input())
print(Pdict.get(Ecall, 'N/A'))

Use two different split operations instead of doing the replace to try to do it in a single split (which just makes things more difficult because now you've lost the information of which separator was which).

First split the original string (on whitespace) to produce a list of comma-separated entries:

>>> user_input = "Joe,123-5432 Linda,983-4123 Frank,867-5309"
>>> user_input.split()
['Joe,123-5432', 'Linda,983-4123', 'Frank,867-5309']

and then split on the commas within each entry so you have a sequence of pairs that you can pass to dict() . You can do the whole thing in one easy line:

>>> dict(entry.split(",") for entry in user_input.split())
{'Joe': '123-5432', 'Linda': '983-4123', 'Frank': '867-5309'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM