Skip to content

Instantly share code, notes, and snippets.

@Ostapp
Created February 14, 2016 20:25
Show Gist options
  • Save Ostapp/0aba8172dbf63d963dfe to your computer and use it in GitHub Desktop.
Save Ostapp/0aba8172dbf63d963dfe to your computer and use it in GitHub Desktop.
colors_list = ['blue', 'blue', 'green', 'yellow',
'blue', 'green', 'red']
sample_dict = {
'a': 1,
'b': 'hello',
'c': [1, 2, 3]
}
sample_dict['c']
# value
sample_dict['a']
# not existing -> KeyError
# or with .get(): no KeyError, None
sample_dict.get('a')
sample_dict.get('a', 'hello')
# left side: .keys()
# py2
sample_dict.keys()
# py3
list(sample_dict.keys())
# right side: .values()
# (key, value): .items()
# 1. keys are unique
# 2. keys are not ordered
# test if key exists in dict: 'key' in mydict
# if key in dict
def count_colors_if(colors_list):
counts = dict()
for color in colors_list:
if color in counts:
counts[color] += 1
# counts[color] = counts[color] + 1
else:
counts[color] = 1
print counts
return counts
# dict.get()
def count_colors_get(colors_list):
counts = dict()
for color in colors_list:
counts[color] = counts.get(color, 0) + 1
print counts
return counts
# dict.setdefault()
def count_colors_setdefault(colors_list):
counts = dict()
for color in colors_list:
counts.setdefault(color, 0)
counts[color] += 1
print counts
return counts
# dict.fromkeys()
def count_colors_fromkeys(colors_list):
counts = dict.fromkeys(colors_list, 0)
for color in colors_list:
counts[color] += 1
return counts
# list.count() + set()
def count_colors_count_set(colors_list):
counts = dict()
for color in set(colors_list):
counts[color] = colors_list.count(color)
return counts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment