Adding a Key-Value Pair to a Python Dictionary: An Example Code

Using the Counter() method, one can identify the frequency of elements. To locate elements with multiple keys, list comprehension can be utilized. In certain cases involving dictionaries, there may be a need to retain those that share similar key values in another dictionary.


Perhaps, it would be necessary to include them individually. For instance:

d = {
    'key' : issue.jira_key,
    'type' : issue.fields.issue_type,
    'creator' : issue.fields.creator,
    'resolution' : issue.fields.resolution
fields = issue.fields  # For brevity
if hasattr(fields, "custom_field_123"):
    d['system_change'] = fields.custom_field_123
if hasattr(fields, "custom_field_456"):
    d['system_resources'] = fields.custom_field_456
if hasattr(fields, "custom_field_789"):
    d['system_backup'] = fields.custom_field_789

Assuming you are using Python 3.8 or later, and none of the field values are empty or None, you could minimize redundancy by utilizing


in combination with a defaulting



if value := getattr(fields, "custom_field_123", None):
    d['system_change'] = value
if value := getattr(fields, "custom_field_456", None):
    d['system_resources'] = value
if value := getattr(fields, "custom_field_789", None):
    d['system_backup'] = value

Frequently Asked Questions