printing a mixed type dictionary with format in python

  • Last Update :
  • Techknowledgy :

You can use round for rounding the floats to a given precision. To identify floats use isinstance:

>>> {
   k: round(v, 2) if isinstance(v, float)
   else v
   for k,
   v in d.iteritems()
} {
   'a': 'Ali',
   'p': 3.14,
   'c': 0.24,
   'b': 2341
}

help on round:

>>> print round.__doc__
round(number[, ndigits]) - > floating point number

Round a number to a given precision in decimal digits(
   default 0 digits).
This always returns a floating point number.Precision may be negative.

You can create a subclass of dict and override the behaviour of __str__:

class my_dict(dict):
   def __str__(self):
   return str({
         k: round(v, 2) if isinstance(v, float)
         else v
         for k,
         v in self.iteritems()
      })
      ...
      >>>
      d = my_dict({
         'a': 'Ali',
         'b': 2341,
         'c': 0.2424242421,
         'p': 3.141592
      }) >>>
      print d {
         'a': 'Ali',
         'p': 3.14,
         'c': 0.24,
         'b': 2341
      } >>>
      "{}".format(d)
"{'a': 'Ali', 'p': 3.14, 'c': 0.24, 'b': 2341}" >>>
d {
   'a': 'Ali',
   'p': 3.141592,
   'c': 0.2424242421,
   'b': 2341
}

So to beautify your dictionary:

newdict = {}
for x in d:
   if isinstance(d[x], float):
   newdict[x] = round(d[x], 2)
else:
   newdict[x] = d[x]

you could also do:

newdict = {}
for x in d:
   if isinstance(d[x], float):
   newdict[x] = float("%.2f" % d[x])
else:
   newdict[x] = d[x]

Suggestion : 2

Check out this tutorial to know how to format string and other data types in Python using the format function. You’ll also see several examples such as format and justify strings, padding and align numbers to adjust the print output.,Python format function allows printing an integer in the octal style. The symbol ‘o’ after the colon inside the parenthesis notifies to display a number in octal format.,A float data type also has a couple of variations which you can style using the Python format function.,2 Format a Python string2.1 Basic string formatting2.2 Padding and align strings2.3 Justify a variable string expansion

The simplest case while calling the Python format function is to have a single formatter. Below is the syntax to use it.

Format syntax: '{}'.format(param)

   *
   Description:
   **
   '{}': It is the format target, i.e., the placeholder. **
   param: It can be a string, integer, float, or any of the collection types. **
   Return: It returns a formatted output with the input argument substituting the placeholder.

See a quick illustration:

>>> '{}'.format('Formatting a String in Python')
'Formatting a String in Python'

A slightly complicated way to call the Python format function is to supply more than one formatter at a time. Below is the syntax to use it.

Format syntax: '{} {}'.format(arg1, arg2)

   *
   Description:
   **
   '{} {}': We can have multiple placeholders. **
   arg1, arg2: They can be a string, integer, float, or any of the collection types. **
   Return: It returns a formatted output with the input argument substituting the placeholder.

Combine two string literals and print them using the format function.

>>> first = "Hello" >>>
   second = "World" >>>
   print('{} {}'.format(first, second))
Hello World

Let’s align a string to the right with spaces.

>>> print(format("Hello", ">10s"))
Hello

Suggestion : 3

last modified December 15, 2021

1._
#!/usr/bin/env python

# create_dict.py

weekend = {
   "Sun": "Sunday",
   "Mon": "Monday"
}
vals = dict(one = 1, two = 2)

capitals = {}
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"

d = {
   i: object() for i in range(4)
}

print(weekend)
print(vals)
print(capitals)
print(d)

In the example, we create four dictionaries in four different ways. Later we print the contents of these dictionaries to the console.

weekend = {
   "Sun": "Sunday",
   "Mon": "Monday"
}

We create a weekend dictionary using dictionary literal notation. The key-value pairs are enclosed by curly brackets. The pairs are separated by commas. The first value of a pair is a key, which is followed by a colon character and a value. The "Sun" string is a key and the "Sunday" string is a value.

vals = dict(one = 1, two = 2)

In the third way an empty capitals dictionary is created. Three pairs are added to the dictionary. The keys are inside the square brackets, the values are located on the right side of the assignment.

d = {
   i: object() for i in range(4)
}

A dictionary is created using a dictionary comprehension. The comprehension has two parts. The first part is the i: object expression, which is executed for each cycle of a loop. The second part is the for i in range(4) loop. The dictionary comprehension creates a dictionary having four pairs, where the keys are numbers 0, 1, 2, and 3 and the values are simple objects.

$ ./create_dict.py
{'Sun': 'Sunday', 'Mon': 'Monday'}
{'two': 2, 'one': 1}
{'svk': 'Bratislava', 'dnk': 'Copenhagen', 'deu': 'Berlin'}
{0: <object object at 0xb76cb4a8>, 1: <object object at 0xb76cb4b0>,
2: <object object at 0xb76cb4b8>, 3: <object object at 0xb76cb4c0>}

Suggestion : 4

Last Updated : 25 Jul, 2022

Output:

{
   1: 'Geeks',
   2: 'For',
   3: 'Geeks'
}

Suggestion : 5

So far we’ve encountered two ways of writing values: expression statements and the print() function. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout. See the Library Reference for more information on this.),Another variant of the dumps() function, called dump(), simply serializes the object to a text file. So if f is a text file object opened for writing, we can do this:,File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects.,Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

>>> year = 2016 >>>
   event = 'Referendum' >>>
   f 'Results of the {year} {event}'
'Results of the 2016 Referendum'
>>> yes_votes = 42_572_654 >>>
   no_votes = 43_132_495 >>>
   percentage = yes_votes / (yes_votes + no_votes) >>>
   '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes  49.67%'
>>> s = 'Hello, world.' >>>
   str(s)
'Hello, world.' >>>
repr(s)
"'Hello, world.'" >>>
str(1 / 7)
'0.14285714285714285' >>>
x = 10 * 3.25 >>>
   y = 200 * 200 >>>
   s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' >>>
   print(s)
The value of x is 32.5, and y is 40000... >>>
   # The repr() of a string adds string quotes and backslashes:
   ...hello = 'hello, world\n' >>>
   hellos = repr(hello) >>>
   print(hellos)
'hello, world\n' >>>
# The argument to repr() may be any Python object:
   ...repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
>>>
import math
   >>>
   print(f 'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
>>> table = {
      'Sjoerd': 4127,
      'Jack': 4098,
      'Dcab': 7678
   } >>>
   for name, phone in table.items():
   ...print(f '{name:10} ==> {phone:10d}')
   ...
   Sjoerd == > 4127
Jack == > 4098
Dcab == > 7678
>>> animals = 'eels' >>>
   print(f 'My hovercraft is full of {animals}.')
My hovercraft is full of eels. >>>
   print(f 'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.

Suggestion : 6

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.,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.,If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary.,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.

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())))