Skip to content

Instantly share code, notes, and snippets.

@Roger-Wu
Last active June 18, 2016 13:52
Show Gist options
  • Save Roger-Wu/7224aec6741471c888ca1b6d924fa4d1 to your computer and use it in GitHub Desktop.
Save Roger-Wu/7224aec6741471c888ca1b6d924fa4d1 to your computer and use it in GitHub Desktop.
# init a dict
d = dict()
d = {}
d = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # like js object
# get
d['Name'] # 'Zara'
d['Gender'] # KeyError # Don't use this
# dict.get(key, default=None)
d.get('Name') # 'Zara'
d.get('Gender') # None
d.get('Gender', 'male') # 'male'
# set
d['Age'] = 8
# get if exist, set if not exist
# dict.setdefault(key, default=None)
d.setdefault('Age', 0) # return 0, but d['Age'] is kept 8
d.setdefault('Gender', 'male') # d['Gender'] = 'male' and return 'male'
# get all keys as list
d.keys()
# get all values as list
d.values()
# get all key-value pairs
d.iteritems()
# iterate through all key-value pairs
for key, value in d.iteritems():
@erichoco
Copy link

# set default values as lists (dict, tuple, etc.)
s = defaultdict(list)
count = [('apple', 5), ('bird', 4), ('cow', 3)]
for k, v in count:
  # set s[k] and init as []
  s[k].append(v)

# s['apple'] = [5], s['bird'] = [4], s['cow'] = [3]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment