Check if a given key already exists in a dictionary
in
tests for the existence of a key in a dict
:
d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
Use dict.get()
to provide a default value when the key does not exist:
d = {}
for i in range(10):
d[i] = d.get(i, 0) + 1
To provide a default value for every key, either use dict.setdefault()
on each assignment:
d = {}
for i in range(10):
d[i] = d.setdefault(i, 0) + 1
or use defaultdict
from the collections
module:
from collections import defaultdict
d = defaultdict(int)
for i in range(10):
d[i] += 1
How can I check if a key exists in a dictionary?
if key in array:
# do something
Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.
Check if a given key already exists in a dictionary and increment it
You are looking for collections.defaultdict
(available for Python 2.5+). This
from collections import defaultdict
my_dict = defaultdict(int)
my_dict[key] += 1
will do what you want.
For regular Python dict
s, if there is no value for a given key, you will not get None
when accessing the dict -- a KeyError
will be raised. So if you want to use a regular dict
, instead of your code you would use
if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1
Python Dictionary Check if Key Exists
Let's note up front that in python a 'dictionary' is a data structure. You're using a third-party library to perform dictionary lookups (as in lexical meanings).
You also need to know how to tell if a python dictionary data structure contains a key. Keep these uses of the word 'dictionary' separate in your mind or you will rapidly get confused. In most python contexts people will assume 'dictionary' means the data structure, not a lexical dictionary like Webster's.
from PyDictionary import PyDictionary
dictionary=PyDictionary()
meanings = dictionary.meaning("test")
if 'Noun' in meanings and 'Verb' in meanings:
#do everything
elif 'Noun' in meanings:
#do something
elif 'Verb' in meanings:
#do something else
Check if value already exists within list of dictionaries and if it does update the counter
If you need your data to be in the format you show, and don't want to incur the cost of iterating over that list for every addition, that's not a problem. All you have to do is build an index for that data structure. The index will be a map with keys that are colors and values that are the index of that color in your original structure. You build this index first, and then you use it to process new entries efficiently. Here's how that goes:
colour_dict = [
{'main_colour': 'red', 'count': 1},
{'main_colour': 'blue', 'count': 5},
{'main_colour': 'green', 'count': 10},
]
colours = ["blue", "blue", "red", "greed", "red", "black"]
# Build an index mapping colors to positions in the 'colour_dict' list
index = {}
for i, entry in enumerate(colour_dict):
index[entry['main_colour']] = i
# Iterate over the new values, tallying them in the original structure, and
# adding new entries to both the original structure and the index when
# we discover colors that aren't yet in our structure. Note that there
# is just a single lookup per addition to the structure. No per-addition
# iteration here.
for colour in colours:
if colour in index:
colour_dict[index[colour]]['count'] += 1
else:
index[colour] = len(colour_dict)
colour_dict.append({'main_colour': colour, 'count': 1})
# Show the updated original structure
print(colour_dict)
Result:
[
{'main_colour': 'red', 'count': 3},
{'main_colour': 'blue', 'count': 7},
{'main_colour': 'green', 'count': 10},
{'main_colour': 'greed', 'count': 1},
{'main_colour': 'black', 'count': 1}
]
I am a teacher of programming, and I think this question is an opportunity to highlight an often overlooked technique. You don't have to change your existing data structure that isn't efficient to look things up in to be able to look things up in it efficiently. You can rather build an index into that structure that is efficient to look things up in that points back to the original structure for storage. This is a sort of "have your cake and eat it too" situation. It's worth grasping so you can have it in your bag of tricks.
This is like maintaining an index at the back of a book rather than restructuring the book's content to be easier to search for individual concepts at the cost of making it less valuable to read from front to back. A book index likewise gives you the best of both worlds.
If key already exists in a dict, how to add multiple values to it (Python)
Save every value as a list
. If the key exists, append
to the list.
contacts = {}
for execution_step in execution_steps["steps"]:
main_execution_context = get_execution_context(execution_step["url"])
contact_phone = main_execution_context["contact"]
if contact_phone not in contacts:
contacts[contact_phone] = list()
contacts[contact_phone].append(main_execution_context["id"])
Edit:
To add new keys:
contacts["example_number"] = list()
contacts['example_number'].append(main_execution_context["id"])
Or:
contacts["example_number"] = [main_execution_context["id"]]
How to select a certain key value and skip if a certain key is not present in the list of dictionaries?
You can use a list comprehension that will check for each dictionary if the key name
belongs to the dictionary list of keys.
dicts = [{'email': 'harimsri@math.uvic.ca', 'gid': '5b869a4fe1cd8e14a38d67b5', '_id': '53f49508dabfaeb4c677b4a4', 'name': 'Hiromasa Habuchi', 'org': 'Department of Mathematics and Statistics, University of Victoria, Victoria, BC, V8W 3R4, Canada', 'orgid': '5f71b2841c455f439fe3c6c9'},
{'_id': '53f43522dabfaee4dc7780b2'},
{'_id': '560175f745cedb3395e5a530'}]
[d for d in dicts if 'name' in d.keys()]
Output:
[{'_id': '53f49508dabfaeb4c677b4a4',
'email': 'harimsri@math.uvic.ca',
'gid': '5b869a4fe1cd8e14a38d67b5',
'name': 'Hiromasa Habuchi',
'org': 'Department of Mathematics and Statistics, University of Victoria, Victoria, BC, V8W 3R4, Canada',
'orgid': '5f71b2841c455f439fe3c6c9'}]
Related Topics
Take a Screenshot Via a Python Script on Linux
Pycharm and Sys.Argv Arguments
Execute Python Script Via Crontab
How to Make a Python Script Run Like a Service or Daemon in Linux
Python Pysftp Get_R from Linux Works Fine on Linux But Not on Windows
Why Is Printing to Stdout So Slow? Can It Be Sped Up
Python Ftp Get the Most Recent File by Date
What Do I Need to Read Microsoft Access Databases Using Python
How to Activate Virtualenv in Linux
Generator Expressions Vs. List Comprehensions
How to Pass Arguments to a Button Command in Tkinter
How Are Iloc and Loc Different
Difference Between '/' and '//' When Used For Division
Deploying a Minimal Flask App in Docker - Server Connection Issues
What's the Difference Between 'Raw_Input()' and 'Input()' in Python 3