-1

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?

azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

1

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.

DraftyHat
  • 428
  • 1
  • 2
  • 6
  • 1
    np.nan seems better for default i.e. `metadatda metadata.get("infer_tags", np.nan) != old_resource_map[id].get("infer_tags", np.nan)`, since np.nan also has the property that `np.nan != np.nan` evaluates to True. – DarrylG Sep 04 '22 at 14:03
  • Thanks DarrylG, that is better! Answer updated to include np.nan. – DraftyHat Sep 04 '22 at 14:53