Answers for "python key"

14

keys in python

car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
# the keys are like variables in dictionary which saves a value

x = car.keys()

print(x)
Posted by: Guest on March-08-2021
14

python get dictionary keys

# To get all the keys of a dictionary use 'keys()'
newdict = {1:0, 2:0, 3:0}
newdict.keys()
# Output:
# dict_keys([1, 2, 3])
Posted by: Guest on February-21-2020
10

python dict

# 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
Posted by: Guest on June-05-2020

Python Answers by Framework

Browse Popular Code Answers by Language