check key is present in python dictionary [duplicate] - python

This question already has answers here:
Check if a given key already exists in a dictionary
(16 answers)
How to check if a key exists in an inner dictionary inside a dictionary in python?
(3 answers)
Closed 5 years ago.
Below is the "data" dict
{' node2': {'Status': ' online', 'TU': ' 900', 'Link': ' up', 'Port': ' a0a-180', 'MTU': ' 9000'}, ' node1': {'Status': ' online', 'TU': ' 900', 'Link': ' up', 'Port': ' a0a-180', 'MTU': ' 9000'}}
I am trying key node2 is present or not in data dict in below code but it is not working. Please help
if 'node2' in data:
print "node2 Present"
else:
print "node2Not present"

if 'node2' in data:
print "node2 Present"
else:
print "node2Not present"
This is a perfectly appropriate way of determining if a key is inside a dictionary, unfortunately 'node2' is not in your dictionary, ' node2' is (note the space):
if ' node2' in data:
print "node2 Present"
else:
print "node2Not present"

Check key is present in dictionary :
data = {'node2': {'Status': ' online', 'TU': ' 900', 'Link': ' up', 'Port': ' a0a-180', 'MTU': ' 9000'}, ' node1': {'Status': ' online', 'TU': ' 900', 'Link': ' up', 'Port': ' a0a-180', 'MTU': ' 9000'}}
In python 2.7 version:
has_key()-Test for the presence of key in the dictionary.
if data.has_key('node2'):
print("found key")
else:
print("invalid key")
In python 3.x version:
key in d - Return True if d has a key, else False.
if 'node2' in data:
print("found key")
else:
print("invalid key")

Related

It's showing \n when printing the list [duplicate]

This question already has answers here:
How can I remove a trailing newline?
(27 answers)
Handling extra newlines (carriage returns) in csv files parsed with Python?
(6 answers)
Closed last month.
The output:
{'name': 'Peter', 'surname': ' Abdilla', 'DOB': ' 22/02/1986', 'mobileNo': '79811526', 'locality': ' Zabbar\n'}
{'name': 'John', 'surname': ' Borg', 'DOB': ' 12/04/1982', 'mobileNo': '99887654', 'locality': ' Paola\n'}
The expected output is supposed to be:
{'name': 'Peter', 'surname': ' Abdilla', 'DOB': ' 22/02/1986', 'mobileNo': '79811526', 'locality': ' Zabbar'}
{'name': 'John', 'surname': ' Borg', 'DOB': ' 12/04/1982', 'mobileNo': '99887654', 'locality': ' Paola'}
Each line in CSV has an endLine character which is '\n', so when you try to read the contents of the csv file line by line, '\n' will also be in the string.
So, we just need to replace the '\n' with an empty string.
To fix this, use the python's string replace() function.
while True:
x = file.readline()
x = x.replace('\n', '')
if x == '':
break
else:
value = x.split(',')
contact = dict(tuple(zip(keys,value)))
filename.append(contact)

How can I split keys of dictionary values using the comma?

The dictionary value mentioned below
dict = {'Incident, INC': 'Incident',
'SR, Service Request': 'Service Request',
'RCA ticket, Task': 'Problem',
'OCM, Alert': 'Change',
'Change': 'Minor enhancements'}
I need to map the dictionary values this
expect dictionary = {
'INC': 'Incident',
'Incident': 'Incident',
'Inc': 'Incident',
'Change': 'Minor Enchancement',
'SR': 'ServiceRequest',
'ServiceRequest': 'ServiceRequest'
}
I need to add more one condition given dictionary would the read given list if any of the value match it should the dict value or else it should return like Unspecified.
input ---->
new_list= ['Incident','INC','SR','Change','ABC']
Expected output --->
new_list = ['Incident','Incident','Minor Enchancement','Service Request','others']
My code does not work.
reversed_dict = {}
for key in my_dict:
items = [x.strip() for x in my_dict[key].split()]
for i in items:
reversed_dict[i] = key
Is this what you're looking for?
rdict = {}
for key in dict:
if any(list(map(lambda char: char in key, ','))):
k = key.split(',')
else: k = [key]
for i in k:
rdict[i.strip()] = dict[key]
print (rdict)
Returns:
{' Alert': 'Change',
' INC': 'Incident',
' Service Request': 'Service Request',
' Task': 'Problem',
'Change': 'Minor enhancements',
'Incident': 'Incident',
'OCM': 'Change',
'RCA ticket': 'Problem',
'SR': 'Service Request'}

Limiting the output

I made a dictionary using .groupdict() function, however, I am having a problem regarding elimination of certain output dictionaries.
For example my code looks like this (tweet is a string that contains 5 elements separated by || :
def somefuntion(pattern,tweet):
pattern = "^(?P<username>.*?)(?:\|{2}[^|]+){2}\|{2}(?P<botprob>.*?)(?:\|{2}|$)"
for paper in tweet:
for item in re.finditer(pattern,paper):
item.groupdict()
This produces an output in the form:
{'username': 'yashrgupta ', 'botprob': ' 0.30794588629999997 '}
{'username': 'sterector ', 'botprob': ' 0.39391528649999996 '}
{'username': 'MalcolmXon ', 'botprob': ' 0.05630123819 '}
{'username': 'ryechuuuuu ', 'botprob': ' 0.08492567222000001 '}
{'username': 'dpsisi ', 'botprob': ' 0.8300337045 '}
But I would like it to only return dictionaries whose botprob is above 0.7. How do I do this?
Specifically, as #WiktorStribizew notes, just skip iterations you don't want:
pattern = "^(?P<username>.*?)(?:\|{2}[^|]+){2}\|{2}(?P<botprob>.*?)(?:\|{2}|$)"
for paper in tweet:
for item in re.finditer(pattern,paper):
item = item.groupdict()
if item["botprob"] < 0.7:
continue
print(item)
This could be wrapped in a generator expression to save the explicit continue, but there's enough going on as it is without making it harder to read (in this case).
UPDATE since you are apparently in a function:
pattern = "^(?P<username>.*?)(?:\|{2}[^|]+){2}\|{2}(?P<botprob>.*?)(?:\|{2}|$)"
items = []
for paper in tweet:
for item in re.finditer(pattern,paper):
item = item.groupdict()
if float(item["botprob"]) > 0.7:
items.append(item)
return items
Or using comprehensions:
groupdicts = (item.groupdict() for paper in tweet for item in re.finditer(pattern, paper))
return [item for item in groupdicts if float(item["botprob"]) > 0.7]
I would like it to only return dictionaries whose botprob is above 0.7.
entries = [{'username': 'yashrgupta ', 'botprob': ' 0.30794588629999997 '},
{'username': 'sterector ', 'botprob': ' 0.39391528649999996 '},
{'username': 'MalcolmXon ', 'botprob': ' 0.05630123819 '},
{'username': 'ryechuuuuu ', 'botprob': ' 0.08492567222000001 '},
{'username': 'dpsisi ', 'botprob': ' 0.8300337045 '}]
filtered_entries = [e for e in entries if float(e['botprob'].strip()) > 0.7]
print(filtered_entries)
output
[{'username': 'dpsisi ', 'botprob': ' 0.8300337045 '}]

How to change inquiry in lambda to a list? [duplicate]

This question already has answers here:
Filter pandas DataFrame by substring criteria
(17 answers)
Closed 2 years ago.
I'm trying to make a list based on a data frame, where if a string is found under the "question" column, it is added. I seem to have made it work with a singular string, but I am not sure how to apply this to a list.
#pd.set_option("display.max_rows", None, "display.max_columns", None)
pd.set_option('display.max_colwidth', -1)
jp = pd.read_csv('jeopardy.csv', delimiter = ",")
jp = jp.rename(columns = {'Show Number': 'show_number', ' Air Date': 'air_date', ' Round': 'round', ' Category': 'category' , " Value": 'value', ' Question': 'question', ' Answer': 'answer'})
#print(jp.head())
print(jp.info())
jp_df = jp[jp.apply(lambda row: 'King' in row['question'], axis = 1)].reset_index(drop=True)
print(jp_df.info())
I think this is what you want:
pd.set_option("display.max_rows", None, "display.max_columns", None)
pd.set_option('display.max_colwidth', -1)
jp = pd.read_csv('jeopardy.csv', delimiter = ",")
jp = jp.rename(columns = {'Show Number': 'show_number', ' Air Date': 'air_date', ' Round': 'round', ' Category': 'category' , " Value": 'value', ' Question': 'question', ' Answer': 'answer'})
values_wanted = ['King', ' Queen']
jp_list = jp[jp['question'].isin(values_wanted)]

Build python dict items with certain key name and value modification and consolidating all dict

I'm trying build python dict items with certain key name and value modification and consolidating all dict.
#!/usr/bin/python
def Cftemplatebuild():
templateBucketName = {
"NewBucketName" : {
"Description" : "Bucket name",
"Type" : "String",
"Default": "bucketname",
"AllowedPattern" : "[-a-z0-9\\-]*",
"ConstraintDescription" : " Must be lowercase no spaces."
}
}
i = 1
TemplateBucketName = {}
TemplateBucketPolicy = {}
bucketNameWithLink = [('TEST','TEST-LINK'),('PROD','PROD-LINK')]
for items in bucketNameWithLink:
print "ITEMS"
print items[0]
print items[1]
print "BUCKET NAME CREATION"
print 'actual', templateBucketName
templateBucketNamecpy = templateBucketName.copy()
print 'copy',templateBucketNamecpy
templateBucketNamecpy['NewBucketName'+str(i)] =
templateBucketNamecpy.pop('NewBucketName')
print 'Modified key name', templateBucketNamecpy
templateBucketNamecpy['NewBucketName'+str(i)]['Default'] = items[0]
templateBucketNamecpy1 = templateBucketNamecpy.copy()
print 'Modfied key value',templateBucketNamecpy
print 'Copy Modified key value',templateBucketNamecpy1
print "templateBucketName-1"
print TemplateBucketName
TemplateBucketName.update(templateBucketNamecpy1)
print TemplateBucketName
#templateBucketName['NewBucketName'] =
templateBucketName.pop('NewBucketName'+str(i))
print "templateBucketName-revert"
#print TemplateBucketName
print 'EnD actual',templateBucketName
print "BUCKET NAME CREATION ENDS"
i= i + 1
if __name__ == "__main__":
Cftemplatebuild()
Expected output:
{'NewBucketName1': {'Default': 'TEST', 'AllowedPattern': '[-a-z0-9\-]', 'Type': 'String', 'Description': 'Bucket name', 'ConstraintDescription': ' Must be lowercase no spaces.'}, 'NewBucketName2': {'Default': 'PROD', 'AllowedPattern': '[-a-z0-9\-]', 'Type': 'String', 'Description': 'Bucket name', 'ConstraintDescription': ' Must be lowercase no spaces.'}}
Actual output obtained:
{'NewBucketName1': {'Default': 'PROD', 'AllowedPattern': '[-a-z0-9\-]', 'Type': 'String', 'Description': 'Bucket name', 'ConstraintDescription': ' Must be lowercase no spaces.'}, 'NewBucketName2': {'Default': 'PROD', 'AllowedPattern': '[-a-z0-9\-]', 'Type': 'String', 'Description': 'Bucket name', 'ConstraintDescription': ' Must be lowercase no spaces.'}}

Categories

Resources