This question already has answers here:
Check if a given key already exists in a dictionary
(16 answers)
Closed 6 months ago.
Im trying to build a list through list comprehension in python.
What I have so far, and it works:
modified_list = [
{id: metadata}
for id, metadata in new_resource_map.items()
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"]
]
My list called: modified_list
Every item in it is dictionary {id: metadata}
I want to add one more thing and it will look like that:
modified_list = [
{id: metadata}
for id, metadata in new_resource_map.items()
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"] **or
metadata["infer_tags"] != old_resource_map[id]["infer_tags"]**
]
The problem is what the last part:
or metadata["infer_tags"] != old_resource_map[id]["infer_tags"]
The problem is not all of the files have that field ("infer_tags").
I wanna do this last thing only after I check if this field is existing.
Is anyone know to do that?
as Mechanic Pig suggests:
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"] or
metadata.get("infer_tags", np.nan) != old_resource_map[id].get("infer_tags", np.nan)
Note that the default values used in the get() calls must not be valid values for infer_tags fields for this to be reliable.
Related
This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 12 months ago.
I have a list of Full Names, where Forenames and Surnames are seperated by a comma, for example:
Authors = ['Shakespeare, William', 'Dafoe, Daniel', 'Pilcher, Rosamunde']
I need a new list that contains only the Surnames, not the Forenames:
AuthorsSurname = ['Shakespeare', 'Dafoe', 'Pilcher']
How can I get there? I tried to search the Authors list with
regexAuthors = re.compile(r',$')
AuthorsSurname = (regexAuthors.findall(Authors))
to match all entries until the comma and create a new list, but it says I cannot use "Authors" as an argument here because it is not a string.
(the linked topic did not help)
Authors = ['Shakespeare, William', 'Dafoe, Daniel', 'Pilcher, Rosamunde']
surname = [val.split(",")[0] for val in Authors]
# ['Shakespeare', 'Dafoe', 'Pilcher']
This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Nested For Loops Using List Comprehension [duplicate]
(4 answers)
How to frame two for loops in list comprehension python
(6 answers)
Closed 1 year ago.
I do not think real python, tutorials point, or even admired and helpful Al Sweigert has covered a return statement this outlandish! 🤯👽
The code can be found freely available on the Internet at this URL: https://github.com/odoo/odoo/blob/11.0/odoo/osv/expression.py My question concerns the code at lines 715-737. I am most confused by lines 732-736.
Please see the function where the confusing return statement appears (lines 715-737):
def to_ids(value, comodel):
""" Normalize a single id or name, or a list of those, into a list of ids
:param {int,long,basestring,list,tuple} value:
if int, long -> return [value]
if basestring, convert it into a list of basestrings, then
if list of basestring ->
perform a name_search on comodel for each name
return the list of related ids
"""
names = []
if isinstance(value, pycompat.string_types):
names = [value]
elif value and isinstance(value, (tuple, list)) and all(isinstance(item, pycompat.string_types) for item in value):
names = value
elif isinstance(value, pycompat.integer_types):
return [value]
if names:
return list({
rid
for name in names
for rid, rname in comodel.name_search(name, [], 'ilike', limit=None)
})
return list(value)
Given the code above I am very confused by this return statement (lines 732-736):
return list({
rid
for name in names
for rid, rname in comodel.name_search(name, [], 'ilike', limit=None)
})
So,
1.) a list is returned.
2.) There are handle-bar brackets around the code meaning the code is a set or a dictionary?
3.) How is there a for loop followed by another for loop on the next line but both for loops are on the same column?
4.) How is the 'name' variable in the first for loop referenced in the second for loop when both loops have the exact same indentation?
5.) Why is 'rid' on a line by itself without any commas? How is this syntactically correct?
This question already has answers here:
Edit the values in a list of dictionaries?
(4 answers)
Closed 1 year ago.
I have the following JSON, I want to be able to get the value for a certain key and update it accordingly.
So for example take a look at the key 'a' in the first JSON object, I want to be able to get its value '2' and then update the value for 'a' to whatever I want. It is important I can work with the value, incase I want to reformat date/time for example and update the key.
All help appreciated
x = "test" : [{
"a":"2",
"b":"12",
"c":"24",
"d":"223",
"e":"23",
},
{"a":"22",
"x":"24",
"c":"25",
"d":"21",
"e":"25",
},
{"a":"12",
"y":"23",
"c":"25",
"d":"23",
"e":"21",
}],
You could do this.
keyFor = 'a'
#get value
aVal = x['test'][0][keyFor]
#change value
aVal = int(aVal) + 2
#substitute in x
x['test'][0][keyFor] = aVal
print(x)
This question already has answers here:
How to get a random value from dictionary?
(19 answers)
Closed 3 years ago.
I want to get a value "element":"value" from a dictionary in python.
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
random.choice(country)
It returns me the following :
File "C:\Users\${username}\AppData\Local\Programs\Python\Python37-32\lib\random.py", line 262, in choice
return seq[i]
KeyError: 10
My aim, is to select a random value and be left with 1 Country - City left in the dictionary.
This does not answer my question : How to get a random value from dictionary in python
You can use the items method to get the pairs, then transform it to a list that supports indexing:
random.choice(list(country.items()))
i think you can implement in following way
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
keys = list(country.keys())
random_key = keys[random.randint(0, len(keys)-1)]
print(country[random_key])
You can make a random.choice from the keys() of the dict for instance.
You could print the values or make a new dict with just that entry:
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
k = random.choice(list(country.keys()))
print(k, country[k])
print({k:country[k]})
First of all, there's no order in a dictionary. The only list can be used for random.sample.
So change your code to random.choice(list(country.items()))
This question already has answers here:
What is getattr() exactly and how do I use it?
(14 answers)
Closed 4 years ago.
following code to start:
products = [{
"id": x.id,
"fabric": x.fabric.name,
"fabricimg": x.fabric.fabric_cover.url,
} for x in entry_obj.all()]
cart_data = {
"products": products,
"total": cart_obj.total
}
return JsonResponse(cart_data)
This works fine for creating my list products with the dictionaries from the x(objects) in entry_obj.all().
But now I have the scenario that I have some x(objects) with no x.fabric.name, and instead will have to use a filler for example a simple string like "noname".
How can I use an if statement in the existing for loop to catch the case of name not existing and instead setting the key fabric to my string value?
I thought of using:
if hasattr(entry_obj,"name") > "fabric": x.fabric.name
else > "fabric": "noname"
But I'm unsure where to put it in the for loop plus how to iterate through the x(objects) in entry_obj for that matter so I can still give Json the right cart_data.
Use getattr with the 3rd default argument:
products = [{'id': x.id, 'fabric': getattr(x.fabric, 'name', 'noname'),
'fabricimg': x.fabric.fabric_cover.url} for x in entry_obj.all()]