Make statement more clear: checking object for key in dictionary
First, you can test and get an existing value with optional binding,
and then append (or set) all new items:
if let oldItems = dict[key] {
dict[key] = oldItems + items
} else {
dict[key] = items
}
This can be simplified with the nil-coalescing operator ??
:
dict[key] = (dict[key] ?? []) + items
In Swift 4 you can simply use the subscript method with a default value:
dict[key, default: []] += items
// Or:
dict[key, default: []].append(contentsOf: items)
Self-contained example:
var dict = ["foo": [1, 2, 3]]
dict["foo", default: []] += [4, 5]
dict["bar", default: []] += [6,7]
print(dict) // ["bar": [6, 7], "foo": [1, 2, 3, 4, 5]]
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 remove a key from a Python dictionary?
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop()
:
my_dict.pop('key', None)
This will return my_dict[key]
if key
exists in the dictionary, and None
otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')
) and key
does not exist, a KeyError
is raised.
To delete a key that is guaranteed to exist, you can also use:
del my_dict['key']
This will raise a KeyError
if the key is not in the dictionary.
The most Pythonic way of checking if a value in a dictionary is defined/has zero length
If you know the key is in the dictionary, use
if mydict["key"]:
...
It is simple, easy to read, and says, "if the value tied to 'key' evaluates to True
, do something". The important tidbit to know is that container types (dict, list, tuple, str, etc) only evaluate to True
if their len
is greater than 0.
It will also raise a KeyError
if your premise that a key is in mydict
is violated.
All this makes it Pythonic.
Python - get object - Is dictionary or if statements faster?
I decided to test the two scenarios of 1000 Names and 2 locations
The Test Samples
Team Dictionary:
di = {}
for i in range(1000):
di["Name{}".format(i)] = {'Location': 'result{}'.format(i), 'LocationB':'result{}B'.format(i)}
def get_dictionary_value():
di.get("Name999").get("LocationB")
Team If Statement:
I used a python script to generate a 5000 line function if_statements(name, location):
following this pattern
elif name == 'Name994':
if location == 'Location':
return 'result994'
elif location == 'LocationB':
return 'result994B'
# Some time later ...
def get_if_value():
if_statements("Name999", "LocationB")
Timing Results
You can time with the timeit function to test the time it takes a function to complete.
import timeit
print(timeit.timeit(get_dictionary_value))
# 0.06353...
print(timeit.timeit(get_if_value))
# 6.3684...
So there you have it, dictionary was 100 times faster on my machine than the hefty 165 KB if-statement function.
Delete a dictionary item if the key exists
You can use dict.pop
:
mydict.pop("key", None)
Note that if the second argument, i.e. None
is not given, KeyError
is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.
Delete an element from a dictionary
The del
statement removes an element:
del d[key]
Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary:
def removekey(d, key):
r = dict(d)
del r[key]
return r
The dict()
constructor makes a shallow copy. To make a deep copy, see the copy
module.
Note that making a copy for every dict del
/assignment/etc. means you're going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you're planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in this answer).
Python: Checking if a 'Dictionary' is empty doesn't seem to work
Empty dictionaries evaluate to False
in Python:
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
Thus, your isEmpty
function is unnecessary. All you need to do is:
def onMessage(self, socket, message):
if not self.users:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))
Does dictionary's clear() method delete all the item related objects from memory?
Python documentation on dicts states that del d[key]
removes d[key]
from the dictionary while d.clear()
removes every key, so basically their behavior is the same.
On the memory issue, in Python when you "delete" you are basically removing a reference to an object. When an object is not referenced by any variable nor other object or becomes unreachable, it becomes garbage and can be removed from memory. Python has a garbage collector that from time to time it does this job of checking which objects are garbage and releases the memory allocated for them.
If the object you are deleting from the dictionary is referenced by other variable then it is still reachable, thus it is not garbage so it won't be deleted. I leave you here some links if you are interested in reading about garbage collection in general and python's garbage collection in particular.
- http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)
- http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection
- http://www.doughellmann.com/PyMOTW/gc/
- http://docs.python.org/library/gc.html
Python update a key in dict if it doesn't exist
You do not need to call d.keys()
, so
if key not in d:
d[key] = value
is enough. There is no clearer, more readable method.
You could update again with dict.get()
, which would return an existing value if the key is already present:
d[key] = d.get(key, value)
but I strongly recommend against this; this is code golfing, hindering maintenance and readability.
Related Topics
Swift - Nsurl Fileurlwithpath Not Unwrapped
Allow Line Editing When Reading Input from The Command Line
Firebase Authentication: Linking Multiple Accounts in Swift
Arkit: Place Object on a Plane Doesn't Work Properly
Why Are Image Views Sometimes Not Appearing in Collection View Cells
Tab Bar Item Icons Appear Darker
How to Center Nspopover When Using Swiftui
How to Custom The Image of Mkannotation Pin
Restrictions Around Protocols and Generics in Swift
Cllocationmanager and Tvos - Requestwheninuseauthorization() Not Prompting
Automatic Select a Date in Datepicker in Swift Language
Turn Off Touch for Whole Screen, Spritekit, How
Uipageviewcontroller with Previous and Next Buttons
Post Urlrequest Doesn't Work in Swift 4
Realitykit - Updating Entity's Translation Returns Unexpected Values
Advantage of Computed Properties (Gettable Ones Only) VS. Stored Properties