user18982
0
Q:

dict() python

# decleration
my_dict = {
  'spam': 'eggs',
  'foo': 4,
  100: 'bar',
  2: 0.5
}

# access single values from the dictionary
print(my_dict['spam']) # eggs
print(my_dict['foo']) # 4
print(my_dict[100]) # bar
print(my_dict[2]) # 0.5

# iterate over the dictionary
for key, value in my_dict.items():
  print(key, value)

# get length of the dictionary
print(len(my_dict)) # 4

# modify the dictionary
my_dict['baz'] = 'qux' # adds a pair
my_dict['baz'] = 'quxx' # also updates it
del my_dict['spam'] # removes a pair

# other methods
print(my_dict.copy()) # Returns a copy of the dictionary
print(my_dict.fromkeys('added', 100)) # Returns a dictionary with the specified keys and their values
print(my_dict.get('foo')) # Returns the value of the specified key
print(my_dict.items()) # Returns a list containing a tuple for each key value pair
print(my_dict.keys()) # Returns a list containing the dictionaries keys
print(my_dict.values()) # Returns a list of all the values in the dictionary
my_dict.setdefault('a', 'b') # Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
my_dict.pop('foo') # Removes the element with the specified key
my_dict.popitem() # Removes the last inserted key-value pair
my_dict.update({'baz': 'val'}) # Updates the dictionary with the specified key-value pairs
my_dict.clear() # Removes all the elements from the dictionary
9
# Dictionaries in Python

ages = {"John": 43, "Bob": 24, "Ruth": 76} # Marked by { at beginning and a } at end

# ^^^ Has sets of keys and values, like the 'John' and 43 set. These two values must be seperated by a colon

# ^^^ Sets of values seperated by commas.

2
shapes={"square": 90, "triangle": 60}
1
thisdictionary = {'key':'value','key1':'value1'}
print(thisdictionary['key'])
9

    x = dict(name = "John", age = 36, country = "Norway")
 
1

thisdict =	{

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

print(thisdict)

 
1
nested_dict = { 'dictA': {'key_1': 'value_1'},
                'dictB': {'key_2': 'value_2'}}
1
d = {'key1':'value1','key2':'value2'}
print(d) # to print full dictionary
l=d.keys
print(l)   # to print keys
b=d.values
print(b)#to print values in dictionary
1
#A dictionary has key-value pairs. Here 1,2,3 are the keys and Item1,Item2,Item3 
#are their values respectively. 
dictionaryName = { 1: "Item1", 2: "Item2", 3: "Item3"}

#retrieving value of a particular key
dictionaryName[1]

#retrieving all the keys in a dictionary
dictionaryName.keys()

#retrieving all the values in a dictionary
dictionaryName.values()
0
Dict = {"name": 'Izhaan', "salary": 1234, "age": 23} 
print("\nDictionary with the use of string Keys: ") 
print(Dict)
0

New to Communities?

Join the community