Python: matching a word in dictionary value - python-2.7

Is there a way to search a dictionary value to match a specific word in python 2.7. I tried making use of the any() command, but this doesn't return anything useful, am I on the right track?
dict = {'1' : 'see john run'}
test = 'run'
if any (x in test for x in Dict.values()):
print "true"

You got the right idea, but you need to switch the arguments in the in test
data = {'1' : 'see john run'}
test = 'run'
if any(test in x for x in data.values()):
print "true"

Just try the following:
print test in mydict.values()[0].split()
>>> mydict = {'1' : 'see john run'}
>>> test = 'run'
>>> print test in mydict.values()[0].split()
True
>>>
Also, i'd suggest changing the variable name dict to something else (I used mydict) because dict shadows the built-in.

Related

python - Wrong regex used?

Here is my func:
#register.filter
def load_human_key(key):
"""
load util based on typ for key
return: More readable key
"""
regex = re.findall('[A-Z][^A-Z]*', key)
if regex:
joined_regex = " ".join(regex)
return joined_regex
return key
When I use load_human_key("JsonKey"). It works fine and returns Json Key, but when I use load_human_key("JsonKEY") it returns "Json K E Y"), which is not the behaviour i'd like to implement. Can sb help my function, so that load_human_key("JsonKEY") = load_human_key("JsonKey")? I am completly new to regex.
Thanks!
A regex only cannot change characters from upper case to lower case, so you'll need to map each match to take care of that with Python code.
Not your question, but the naming used in your code is confusing: regex is not the regex, but the list of matches you get from executing one.
Here is how you could do it:
def load_human_key(key):
return re.sub('[A-Z]+[^A-Z]*', lambda m: ' ' + m[0].capitalize(), key).lstrip()

From SAS to Python : substr

I would like to use the function substr(my_var,1,2) of SAS in Python. I tried a lot of functions like contains(), split() but it didn't work.
The functions contains() and split() work only for a string value. I would like to use it on a Python Series without using a for.
Thanks a lot for your help
A string in python can be sliced like any list:
>>> str = 'Hello World'
>>> str[1:3]
'el'
>>> str[1:-2]
'ello Wor'
To get substrings for multiple strings, you can use list comprehensions:
>>> strs = ['Hello World', 'Foobar']
>>> [ str[1:4] for str in strs]
['ell', 'oob']
In python, you may try this:
my_var[1:3]
This gets sub string of my_var from position 1 to 3 (exclusive).

How to check if the user input is in a specific format?

i am very new to coding, and am in need of some assistance, and would like to say sorry for such a novice question, but I could not word the question in a way to easily find help, which i am sure is out there. Anyways, to put it simply, I need to force the user when asked to input text, to have the format 'a=b'.
`message3 = raw_input("Enter a guess in the form a=b:")`
I would like to make it so that if the user does not enter the correct format, 'a=b', some error message will pop up telling them so.
Here's how I would do it, expanding on my comment above. Since you're learning python, it's best if you learn python 3.
import sys
import re
s = input("Enter a guess in the form a=b:")
matched = re.match(r'(.+)=(.+)', s)
if matched is None:
print('enter in the form of a=b')
sys.exit(1)
a, b = matched.groups()
print(a, b)
In the regex, .+ matches a non-empty string. The brackets are a capturing group, so we can get a and b using .groups().
You can try this:
>>> import re
>>> string = raw_input("Enter a guess in the form a=b:")
Enter a guess in the form a=b: Delirious= # Incorrect Format
>>> m = re.match(r'.+=.+', string)
>>> try:
if m.group():
print "Correct Format"
except:
print "The format isn't correct"
"The format isn't correct"
>>>
>>> string = raw_input("Enter a guess in the form a=b:")
Enter a guess in the form a=b: Me=Delirious # Correct Format
>>> m = re.match(r'.+=.+', string)
>>> try:
if m.group():
print "Correct Format"
except:
print "The format isn't correct"
"Correct Format"

Better code then a regex sub() python 2.7

I am trying to find out if there are better faster ways to clean this returned string. Or is this the best way. It works, but more efficient ways are always wanted.
I have a function that returns the following output:
"("This is your:, House")"
I clean it up before printing with:
a = re.sub(r'^\(|\)|\,|\'', '', a)
print a
>>> This is your: House
I also learn a lot from the different ways people do things.
You don't need to use regular expression to do this.
>>> import string
>>> a = '"("This is your:, House")"'
>>> ''.join(x for x in a if x not in string.punctuation)
'This is your House'
>>> tbl = string.maketrans('', '')
>>> a.translate(tbl, string.punctuation)
'This is your House'
s='"("This is your:, House")"'
s.replace('\"','').replace('(','').replace(')','').replace(',','').replace(':','')
'This is your House'

Using integer as dictionary key using dict()

I'm trying to use numbers as my dict key. Is there anyway to initiate the dictionary using dict() method?
This works
mydict = { '100':'hundred', '200':'two hundred'}
This doesn't work?
mydict = dict( 100='hundred' )
The error says 'keyword can't be an expression' and I couldn't find any solution.
Thank you.
I can't understand your question exactly, but you mentioned to use number as dict key right? you just directly initiate it using integer instead string like this..
a = {1:'one',100:'hundered'}
print a
{1: 'one', 100: 'hundrered'}
No, it mist be a valid python identifier, so it cannot start with a number.
You can read where i found it at here in the part about dict
https://docs.python.org/2/library/stdtypes.html#typesmapping
Like the comment above says you can use an int, since dictionaries just hash the string and you get an int anyways, in the case of an int it just hashes to itself. But it doesnt work with dict ()
On that page it shows you can do
mydict = dict (zip ([1], ["one"]))
Which is kinda ugly imo, but seems to get the job done
To use the dict method you need to feed it a list or tuple of lists or tuples.
>>> dict([(100, 'hundred'), (200, 'two hundred')])
{200: 'two hundred', 100: 'hundred'}