proper way of breaking line accessing dictionary

  • Last Update :
  • Techknowledgy :

Parentheses seem to work:

(config_data_dict['foo']['bar']['foobarfoo']
   ['barfoobar']) = something_else

Using operator.setitem. (this is almost the same as described in this answer but to me looks much more readable as it doesn’t have the leading parentheses)

setitem(config_data_dict['foo']['bar']['foobarfoo'],
   'barfoobar', something_else)

Or some prefer the reduce method with operator.getitem. (also alike this answer the reduce approach could be easier on the eyes if you’re getting REALLY deeply nested but I prefer the later as it’s not adding yet another somewhat unnecessary function into the mix)

path = ['foo', 'bar', 'foobarfoo']
reduce(getitem, path, config_data_dict)['barfoobar'] = something_else

Or to allow for more nice indenting use setitem here too

setitem(reduce(getitem, path, config_data_dict),
   'barfoobar', something_else)

You could break inside the [...] (though I'm not really sure which would be considered more readable: breaking after the [, or before the ], or both):

config_data_dict[
   'foo'][
   'bar'
][
   'foobarfoo'
][
   'barfoobar'
] = something_else

As a general rule, either put all the keys on the same line, or put each key on a separate line. This applies to the explicit parenthesization used in other answers, for example,

(config_data_dict['foo']
   ['bar']
   ['foobarfoo']
   ['barfoobar']) = something_else

However, I would just use one or more temporary variables:

d = config_data_dict['foo']['bar']['foobarfoo']
d['barfoobar'] = something_else

Suggestion : 2

We can iterate over the keys of a dictionary one by one, then for each key access its value and print in a separate line i.e.,dict.items() returns an iterable view object of the dictionary that we can use to iterate over the contents of the dictionary, i.e. key-value pairs in the dictionary and print them line by line i.e.,In this article, we will discuss different ways to print line by line the contents of a dictionary or a nested dictionary in python.,We first iterated over the items, i.e. key/value pairs of the dictionary, and for each pair printed the key. As value field is another dictionary, so we again iterated over the key-value pairs in this dictionary and printed its contents i.e. key/value pairs in separate lines.

As dictionary contains items as key-value pairs. So, first, let’s create a dictionary that contains student names and their scores i.e.

# A dictionary of student names and their score
student_score = {
   'Ritika': 5,
   'Sam': 7,
   'John': 10,
   'Aadi': 8
}

Now to print this dictionary, we directly pass it in the print function i.e.

print(student_score)

the output will be like,

{
   'Ritika': 5,
   'Sam': 7,
   'John': 10,
   'Aadi': 8
}

Output:

Ritika: 5
Sam: 7
John: 10
Aadi: 8

We can iterate over the keys of a dictionary one by one, then for each key access its value and print in a separate line i.e.

# A dictionary of student names and their score
student_score = {
   'Ritika': 5,
   'Sam': 7,
   'John': 10,
   'Aadi': 8
}

# Iterate over the keys in dictionary, access value & print line by line
for key in student_score:
   print(key, ' : ', student_score[key])

Suggestion : 3

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −,To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −,(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example −,You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −

1._
#!/usr/bin/python

dict = {
   'Name': 'Zara',
   'Age': 7,
   'Class': 'First'
}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

When the above code is executed, it produces the following result −

dict['Name']: Zara
dict['Age']: 7
3._
#!/usr/bin/python

dict = {
   'Name': 'Zara',
   'Age': 7,
   'Class': 'First'
}
print "dict['Alice']: ", dict['Alice']

When the above code is executed, it produces the following result −

dict['Age']: 8
dict['School']: DPS School
7._
#!/usr/bin/python

dict = {
   'Name': 'Zara',
   'Age': 7,
   'Class': 'First'
}
del dict['Name'];
# remove entry with key 'Name'
dict.clear();
# remove all entries in dict
del dict;
# delete entire dictionary

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

Suggestion : 4

We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.,The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear() method.,While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets [] or with the get() method.,We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values.

While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.

# empty dictionary
my_dict = {}

# dictionary with integer keys
my_dict = {
   1: 'apple',
   2: 'ball'
}

# dictionary with mixed keys
my_dict = {
   'name': 'John',
   1: [2, 4, 3]
}

# using dict()
my_dict = dict({
   1: 'apple',
   2: 'ball'
})

# from sequence having each item as a pair
my_dict = dict([(1, 'apple'), (2, 'ball')])

If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

# get vs[]
for retrieving elements
my_dict = {
   'name': 'Jack',
   'age': 26
}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn 't exist throws error
# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

Output

Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
      print(my_dict['address'])
      KeyError: 'address'

We can also use the del keyword to remove individual items or the entire dictionary itself.

# Removing elements from a dictionary

# create a dictionary
squares = {
   1: 1,
   2: 4,
   3: 9,
   4: 16,
   5: 25
}

# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))

# Output: {
   1: 1,
   2: 4,
   3: 9,
   5: 25
}
print(squares)

# remove an arbitrary item,
return (key, value)
# Output: (5, 25)
print(squares.popitem())

# Output: {
   1: 1,
   2: 4,
   3: 9
}
print(squares)

# remove all items
squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself
del squares

# Throws Error
print(squares)

Here are a few example use cases of these methods.

# Dictionary Methods
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)

# Output: {
   'English': 0,
   'Math': 0,
   'Science': 0
}
print(marks)

for item in marks.items():
   print(item)

# Output: ['English', 'Math', 'Science']
print(list(sorted(marks.keys())))

Suggestion : 5

To create an empty dictionary, first create a variable name which will be the name of the dictionary.,To learn more about the Python programming language, check out freeCodeCamp's Scientific Computing with Python Certification.,Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.,When it comes to values inside a Python dictionary there are no restrictions. Values can be of any data type - that is they can be both of mutable and immutable types.

Then, assign the variable to an empty set of curly braces, {}.

#create an empty dictionary
my_dictionary = {}

print(my_dictionary)

#to check the data type use the type() function
print(type(my_dictionary))

#output

#{}
#<class 'dict'>

It acts as a constructor and creates an empty dictionary:

#create an empty dictionary
my_dictionary = dict()

print(my_dictionary)

#to check the data type use the type() function
print(type(my_dictionary))

#output

#{}
#<class 'dict'>

The general syntax for this is the following:

dictionary_name = {
   key: value
}

You would achieve this by using dict() and passing the curly braces with the sequence of key-value pairs enclosed in them as an argument to the function.

#create a dictionary with dict()
my_information = dict({'name': 'Dionysia' ,'age': 28,'location': 'Athens'})

print(my_information)

#check data type
print(type(my_information))

#output

#{'name': 'Dionysia', 'age': 28, 'location': 'Athens'}
#<class 'dict'>

The general syntax for the method is the following:

dictionary_name = dict.fromkeys(sequence, value)

Suggestion : 6

It doesn’t matter what order we write the pairs. The values in a dictionary are accessed with keys, not with indices, so there is no need to care about ordering.,As we saw earlier with strings and lists, dictionary methods use dot notation, which specifies the name of the method to the right of the dot and the name of the object on which to apply the method immediately to the left of the dot. The parentheses indicate that this method takes no parameters.,The first assignment creates a dictionary named eng2sp; the other assignments add new key-value pairs to the dictionary. We can print the current value of the dictionary in the usual way:,The has_key method takes a key as an argument and returns True if the key appears in the dictionary and False otherwise:

>>> eng2sp = {} >>>
   eng2sp['one'] = 'uno' >>>
   eng2sp['two'] = 'dos'
>>> print eng2sp {
   'two': 'dos',
   'one': 'uno'
}
>>> eng2sp = {
   'one': 'uno',
   'two': 'dos',
   'three': 'tres'
}
>>> print eng2sp['two']
'dos'
>>> inventory = {
      'apples': 430,
      'bananas': 312,
      'oranges': 525,
      'pears': 217
   } >>>
   print inventory {
      'oranges': 525,
      'apples': 430,
      'pears': 217,
      'bananas': 312
   }
>>> del inventory['pears'] >>>
   print inventory {
      'oranges': 525,
      'apples': 430,
      'bananas': 312
   }