I have to read elements of of the following python dictionary:
dict = {'crawler.cmd': 'OS Path for CMD',
's3.failureBucket': 'Failure Bucket Name',
's3.landingBucket': 'Landing Bucket Name',
's3.rawBucket': 'Raw Bucket Name',
'src.name': 'StreamNameUpd'}
As the element name contains dots so, how would I access element with dot in name?
Given your dictionary:
my_dictionary = {'crawler.cmd': 'OS Path for CMD',
's3.failureBucket': 'Failure Bucket Name',
's3.landingBucket': 'Landing Bucket Name',
's3.rawBucket': 'Raw Bucket Name',
'src.name': 'StreamNameUpd'}
You can access any element just by putting its correspondant key in the square brackets like the following:
my_dictionary['crawler.cmd']
Output:
'OS Path for CMD'
Another way to get this:
my_dictionary.get('crawler.cmd')
With get() function you can also define a default value in case the key not in dict:
my_dictionary.get('crawler.cmd', "my_value")
Output:
'OS Path for CMD'
Related
I have a dictionary in the form of a string and I need to add the string_dictionary to the list as a regular dictionary, because I need to enter the list and then the dictionary, like this:
Source[0]["name"]
But, the dictionary in the list is in "" and python not consider it like a dictionary.
dictionary = "{'name': 'liam', 'last name': 'something'}"
Source = [
dictionary,
]
print(Source)
Output:
["{'name': 'liam', 'last name': 'something'}"]
To parse the string to a dictionary, you can use ast.literal_eval:
from ast import literal_eval
dictionary = "{'name': 'liam', 'last name': 'something'}"
Source = [
literal_eval(dictionary),
]
print(Source[0]["name"])
Prints:
liam
Following is my intention
1. read json file with codecs and utf-8 encoding
2. load the json file into python as dictionary
3. iterate through dictionary , if 'categories' key contains value 'Restaurant' then add it to a set ; else continue to next iteration.
Issue: 'categories' key may contain values like 'Restaurant', 'Restaurant and Bristro', 'Restaurant and Bar'.
My if condition should select all these three values not only 'Restaurant'
Sample code as follows
import json
restaurant_ids = set()
# open the json file
with codecs.open(json_file.json, encoding='utf_8') as f:
# iterate through each line (json record) in the file
for b_json in f:
# convert the json record to a Python dict
business = json.loads(b_json)
# if this key is not a restaurant, skip to the next one
if u'Restaurants' not in business[u'categories']:
continue
# add the restaurant business id to our restaurant_ids set
restaurant_ids.add(business[u'business_id'])
print (len(restaurant_ids))
I am getting error at if condition, business[u'categories'] seems to be unicode object, I get following error
Argument of type 'NonType' is not iterable
Any help would be highly appreciated
One of the JSON objects is missing the catagories key.
I'm getting an unexpected result using icontains in my get_or_create call.
Take the following example:
>>>team_name = "Bears"
>>>Team.objects.get(name__icontains=team_name) # returns DoesNotExist as expected
>>>team, created = Team.objects.get_or_create(name__icontains=team_name)
>>>print(created) # Prints True as expected
>>>print(team.name) # Prints an empty string!
Why does this create a team with a blank name rather than "Bears"? The reason I'm using get_or_create here is that if a subsequent user posts something like "BearS" I want to get the correct team, not create a duplicate team with incorrect capitalization.
I think here you should split the get() and create() functionalities instead of using get_or_create(), because the __icontains lookup works for get() only.
Try doing something like this:
>>> team_name = 'Bears'
>>> teams = Team.objects.filter(name__icontains=team_name)
# This will filter the teams with this name
>>> team = teams.first() if teams.exists() else Team.objects.create(name=team_name)
# Now your team is the first element of your previous query (it returns a QuerySet with single element) if it exists
# Otherwise, you create a new Team.
Another option besides wencakisa's answer is to include the defaults parameter in get_or_create, because Django strips lookups containing the __ separator. See answers to this question.
The code would be:
Team.objects.get_or_create(
name__icontains=team_name,
defaults = {
"name": team_name
}
)
The right way to do it is using Django's function get_or_create(). But instead of "icontains", you should use "iexact" (), unless you want an exact match, in wich case you should use just "exact":
Team.objects.get_or_create(
name__iexact=team_name,
defaults = {
"name": team_name
}
)
Outside "defaults" you should put your search terms. If the objects doesn't exist, you should write your creation terms inside 'defaults'
i have list like this
http://google.com:username:password
http://google2.com:username2:password2
how i can give a variable for this list i went give 3 variable Address , username , password
when i do print Address i went this program print for me google.com
and when i do print username i went this program print for me username
As mentioned in the comments, the most straightforward solution may be to put your list into a python dictionary structure with your 3 variables as keys, and each key is associated with individual values:
mydict = [
{
'Address': 'http://google.com',
'username': 'username',
'password': 'password'
},
{
'Address': 'http://google2.com:username2:password2',
'username': 'username2',
'password': 'password2'
}
]
Demo:
We have 2 entries from the original list, so you can specify which entry you want by indexing the dictionary starting from 0 as the first entry
# access 1st entry values
print mydict[0]['Address'] # http://google.com
print mydict[0]['username'] # username
# access 2nd entry values
print mydict[1]['password'] # password2
I need to make UI many2one dopdown list where I can identify users which depend to Manager group role.
Now I have dropdown field:
test = fields.Many2one('res.groups', 'Purchase request type', default=_get_users, track_visibility='onchange')
And I tried to write a function which can identify all users which depend to manager group role.
def _get_users(self):
pickings = self.env['res_groups_users_rel'].search([('gid','=',61)])
pickings_available = []
for picking in pickings:
pickings_available.append(picking)
return pickings_available
And I got an error:
return self.models[model_name]
KeyError: 'res_groups_users_rel'
I don't know how can I change this function and get value from amy2many relation.
I changed my function to:
def _get_users(self):
pickings = self.env['res.groups'].browse(61).users
pickings_available = []
for picking in pickings:
pickings_available.append(picking)
return pickings_available
and field:
test = fields.Many2one('res.users', 'Some text', default=_get_users, track_visibility='onchange')
I logged function _get_users and get values: [res.users(9,), res.users(65,)]
But I still can't get these values on my test field dropdown. What I am doing wrong?
If you are trying to get all users that belong to a group, why not do the following:
self.env['res_groups'].browse(61).users
On a side note, you might get an error, trying to assign a list as default value to a Many2one field.
Also you seem to be assigning users belonging to a group to a field that is specified to store reference to groups.
If you need to have a field to select a user that belongs to group with id 61, you can do the following:
test = fields.Many2one('res.users', 'Some description', domain="[('groups_id', 'in', [61])]")