Skip to content

Instantly share code, notes, and snippets.

@gergob
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gergob/010d80edd977ba2ea51a to your computer and use it in GitHub Desktop.
Save gergob/010d80edd977ba2ea51a to your computer and use it in GitHub Desktop.
#creating a new dictionary with 3 keys : name, age and balance
d = { "name": "John Doe", "age": 44, "balance": 235.5 }
#printing out the values of the dictionary using the kyes
print(d["name"]) # will display "John Doe"
print(d["age"]) # will display 44
print(d["balance"]) # will display 235.5
#using dict to create dictionaries
my_dict_1 = dict(name="John Doe", age=44, balance=235.5)
my_dict_2 = dict({ "name": "John Doe", "age": 44, "balance": 235.5 })
my_dict_3 = dict(zip(["name", "age", "balance"], ["John Doe", 44, 235.5]))
print(my_dict_1) # will print {'age': 44, 'name': 'John Doe', 'balance': 235.5}
print(my_dict_2) # will print {'age': 44, 'name': 'John Doe', 'balance': 235.5}
print(my_dict_3) # will print {'age': 44, 'name': 'John Doe', 'balance': 235.5}
# comparing the three dictionaries shows
# these have the same keys and values
print(my_dict_3 == my_dict_2 == my_dict_1) # will print true
#using a for loop to print out values
for key, val in enumerate(d):
print("{} = {}".format(key,val))
#the dictionary has a method called items()
#which does basically the same
for key, val in d.items():
print("{} = {}".format(key,val))
#index, get and update methods
my_dict_1 = dict(name="John Doe", age=44, balance=235.5)
print(my_dict_1["name"]) # will print "John Doe"
print(my_dict_1.get("name")) # will print "John Doe"
#specifying a value for a non-existing key will add the
#key-value pair to the dictionary
my_dict_1["website"] = "http://example.com"
print(my_dict_1) # will print {'age': 44, 'name': 'Jane Doe', 'website':'http://example.com', 'balance': 235.5}
#using the update method with one named parameter
my_dict_1.update(name = "Jane Doe")
print(my_dict_1) # will print {'age': 44, 'name': 'Jane Doe', 'website':'http://example.com', 'balance': 235.5}
#update can take a dictionary as parameter and will map the keys
my_dict_1.update({"name" = "Jane Doe", "balance" = 500})
print(my_dict_1) # will print {'age': 44, 'name': 'Jane Doe', 'website':'http://example.com', 'balance': 500}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment