Lists and dictionary conversion in python - 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 .splits 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'}

Related

Split string from two pattern based on regex Python

Given a two file path
Z:\home\user\dfolder\NO,AG,GK.jpg
Z:\home\user\dfolder\NI,DG,BJ (1).jpg
The objective is to split each string and store into a dict
Currently, I first split the path using os.path.split to get list of s
s=['NO,AG,GK.jpg','NI,DG,BJ (1).jpg']
and iteratively split the string as below
all_dic=[]
for ds in s:
k=ds.split(",")
kk=k[-1].split('.jpg')[0].split("(")[0] if bool(re.search('\(\d+\)', ds)) else k[-1].split('.jpg')[0]
nval={"f":k[0],"s":k[1],"t":kk}
all_dic.append(nval)
But, I am curious for a regex approach, or any 1 liner .
One liner parsing using regex + inline list parsing:
import re
s = ['NO,AG,GK.jpg', 'NI,DG,BJ (1).jpg']
keys = ['f', 's', 't']
all_dic = [{keys[k]: x for k, x in enumerate(
re.sub("(\s\(\d+\))?(\.jpg)?", "", item).split(','))} for item in s]
print(all_dic)
->
[{'f': 'NO', 's': 'AG', 't': 'GK'}, {'f': 'NI', 's': 'DG', 't': 'BJ'}]
Well, I think this is the easiest way to get the same output without using the split() function.
The regular expression takes only the letters and puts them in a list, so we don't even have to split the string or remove the (1) from it.
import re
s=['NO,AG,GK.jpg','NI,DG,BJ (1).jpg']
all_dic = []
for ds in s:
regex = '[a-zA-Z]+'
k = re.findall(regex,ds) # We extract all the matches (as a list)
nval={'f':k[0],'s':k[1],'t':k[2]} # We create the dictionary
all_dic.append(nval) # We append the dictionary to the list
print(all_dic)
# Output: [{'f': 'NO', 's': 'AG', 't': 'GK'}, {'f': 'NI', 's': 'DG', 't': 'BJ'}]
Also, you have the file extension in k[3], just in case you need it.

Text manipulation to form an equation

a=0.77 ,b=0.2 ,c=0.20, d=0.79 ,z=(c+d), e=(z*a) ,output=(z+e)
I have a text file like above. I need a parser logic that will throw an equation like
output=(0.20+0.79)+((0.20+0.79)*a) what are some efficient ways to do it? Are there any libraries? Thank you!
Primitive method is to work with strings and use replace()
First use split(',') to convert string to list
['a=0.77 ', 'b=0.2 ', 'c=0.20', ' d=0.79 ', 'z=(c+d)', ' e=(z*a) ', 'output=(z+e)']
Next use .strip() to remove spaces from ends and begins.
Next use .split('=') on every element to create nested lists.
[['a', '0.77'], ['b', '0.2'], ['c', '0.20'], ['d', '0.79'], ['z', '(c+d)'], ['e', '(z*a)'], ['output', '(z+e)']]
Next use dict() to create dictionary.
{'a': '0.77',
'b': '0.2',
'c': '0.20',
'd': '0.79',
'e': '(z*a)',
'output': '(z+e)',
'z': '(c+d)'}
And now you can get first 'a' : '0.77 to run .replace('a', '0.77)` on other items in dictionary. And repeate it with other values from dictionary.
So finally you could get dictionary
{'a': '0.77',
'b': '0.2',
'c': '0.20',
'd': '0.79',
'e': '((0.20+0.79)*0.77)',
'output': '((0.20+0.79)+((0.20+0.79)*0.77))',
'z': '(0.20+0.79)'}
and output has string ((0.20+0.79)+((0.20+0.79)*0.77))
import sympy
import pprint
text = 'a=0.77 ,b=0.2 ,c=0.20, d=0.79 ,z=(c+d), e=(z*a) ,output=(z+e)'
parts = text.split(',') # create list
#print(parts)
parts = [item.strip() for item in parts] # remove spaces
#print(parts)
parts = [item.split('=') for item in parts] # create tuples
#print(parts)
parts = dict(parts) # create dict
#print(parts)
pprint.pprint(parts)
for key1, val1 in parts.items():
for key2, val2 in parts.items():
parts[key2] = parts[key2].replace(key1, val1)
pprint.pprint(parts)
print('output:', parts['output'])

How to replace given index in String with Dictionary value in python?

The instructions are to replace certain characters within a string to the corresponding value in the dictionary.
Here is my code:
word = input()
password = ''
wordDict = {
'i': '!',
'a': '#',
'm': 'M',
'B': '8',
'o': '.',
}
for i in range(len(word)):
if word[i] in wordDict.keys():
word.replace(word[i], wordDict.get(word[i]))
i += 1
else:
i += 1
print(word)
The problem with my code is that nothing about the given password is changing nor does it seem to be iterating through the for loop.
Your problem is with this line:
word.replace(word[i], wordDict.get(word[i]))
Strings in Python, as well as many other languages, are immutable, meaning you can't edit the string.
The function you're calling (str.replace) doesn't replace the character in the string, it returns a new str with the character replaced.
The easiest, though naive if you want this to work efficiently, solution is to replace it with this line:
word = word.replace(word[i], wordDict.get(word[i]))

Input string. Associate index to each character in string for a dictionary

I am asking the user to enter a string. I am ultimately trying to pass the string to a dictionary, where the the index of each character is associated with each character in the string.
Ex: Input = CSC120
What I have done so far is entered a string and passed it to a set. The issue is that when I pass it to a set, it passes in : {'1', '2', 'C', '0', 'S'}. It is out of order. I was thinking I would be able to correlate the string to an index once it was passed to the set, but it is out of order and does not duplicate the 'C'.
The plan was to have 2 sets and link them in a dictionary. I am stuck at trying to get the string to be correctly passed to the set.
d = {}
set1 = set()
string1 = input("Enter a string:").upper()
for i in string1:
set1.add(i)
print(set1)
Ultimately the results I am trying to achieve is:
d = { 0:'C', 1:'S', 2:'C', 3:'1', 4:'2', 5:'0'}
It can be done with a dictionary display (aka comprehension):
Input = 'CSC120'
d = {i: c for i, c in enumerate(Input)}
print(d) # -> {0: 'C', 1: 'S', 2: 'C', 3: '1', 4: '2', 5: '0'}
However, it can be done with even less code (and likely more quickly), by passing the dict constructor the an enumeration of the characters in the string (as helpfully pointed-out by #coldspeed in a comment):
d = dict(enumerate(Input))
Here's the documentation for the built-in enumerate() function.

How can I replace certain characters in a string?

I'm relatively new to python(3.5.2) and I'd love some help with my assignment on lists& strings.
I am required to write a code that replaces: e and E with 3, a and A with 4, i and I with 1, o and O with 0 in any given string. Here is my attempt:
s = input("Enter a string: ")
leet = {'a':'4','e':'3','i':'1','o':'0','A':'4','E':'3','I':'1','O':'0'}
for character in s:
if character == leet.keys():
str.replace(leet.keys(),leet.values())
print(s)
This code does not yield any satisfying results for me, I'm wondering if I can use the str.replace method or is there any easier way of doing this?
Thanks!
you can do that in one line using a generator comprehension converted to a string using str.join (Using dict.get with defaults to the input character if not found in dictionary):
s = "a string Entered"
leet = {'a':'4','e':'3','i':'1','o':'0','A':'4','E':'3','I':'1','O':'0'}
crypted = "".join(leet.get(k,k) for k in s)
print(crypted)
result:
4 str1ng 3nt3r3d
replace() method is good. But you use it wrong. Remember that leet.keys() will return a list of all keys in the dictionary. So I suggest this:
s = input("Enter a string: ")
leet = {'a': '4', 'e': '3', 'i': '1', 'o': '0', 'A': '4', 'E': '3', 'I': '1', 'O': '0'}
for k, v in leet.items(): #iterating through dictionary (not string)
s = s.replace(k, v)
print(s)

Categories