Categories
Python Answers

How to count the frequency of the elements in an unordered list with Python?

Sometimes, we want to count the frequency of the elements in an unordered list with Python.

In this article, we’ll look at how to count the frequency of the elements in an unordered list with Python.

How to count the frequency of the elements in an unordered list with Python?

To count the frequency of the elements in an unordered list with Python, we can use the collections.Counter class.

For instance, we write:

import collections

a = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5]
counter = collections.Counter(a)

print(counter)

We pass in the a array as the argument for the collections.Counter constructor.

This returns a Counter instance that has the items in a as keys and the count of each item as their values.

Therefore, counter is:

Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})

Conclusion

To count the frequency of the elements in an unordered list with Python, we can use the collections.Counter class.

Categories
Python Answers

How to use the itertools.groupby() method with Python?

Sometimes, we want to use the itertools.groupby() method with Python.

In this article, we’ll look at how to use the itertools.groupby() method with Python.

How to use the itertools.groupby() method with Python?

To use the itertools.groupby() method with Python, we can call it with an array of tuples and a function to do the grouping.

For instance, we write:

from itertools import groupby

things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"),
          ("vehicle", "speed boat"), ("vehicle", "school bus")]

groups = [(k, [*g]) for k, g in groupby(things, lambda x: x[0])]
print(groups)

We use list comprehension to get the key and group items from g with the * operator.

We call groupby with things and a function that returns the key of the items to group by, which is the first entry in each tuple.

Therefore, groups is:

[('animal', [('animal', 'bear'), ('animal', 'duck')]), ('plant', [('plant', 'cactus')]), ('vehicle', [('vehicle', 'speed boat'), ('vehicle', 'school bus')])]

Conclusion

To use the itertools.groupby() method with Python, we can call it with an array of tuples and a function to do the grouping.

Categories
Python Answers

How to parse a date string and change its format with Python?

Sometimes, we want to parse a date string and change its format with Python.

In this article, we’ll look at how to parse a date string and change its format with Python.

How to parse a date string and change its format with Python?

To parse a date string and change its format with Python, we can use the datetime.datetime.striptime method to parse a date string into a date object.

And then we call strftime to convert the date object back to a string.

For instance, we write:

import datetime

d = datetime.datetime.strptime('Mon Feb 15 2020',
                               '%a %b %d %Y').strftime('%d/%m/%Y')
print(d)

We call datetime.datetime.strptime with the date string and the format string of the date respectively.

%a is the abbreviation of the day of the week.

%b is the abbreviation of the month.

%d is the day of the month.

And %Y is the year.

We then call strftime to return a date string with the format we want.

%m is the 2 digit month.

Therefore, d is '15/02/2020'.

Conclusion

To parse a date string and change its format with Python, we can use the datetime.datetime.striptime method to parse a date string into a date object.

And then we call strftime to convert the date object back to a string.

Categories
Python Answers

How to read JSON from a file with Python?

Sometimes, we want to read JSON from a file with Python.

In this article, we’ll look at how to read JSON from a file with Python.

How to read JSON from a file with Python?

To read JSON from a file with Python, we can use the json.loads method.

For instance, we write:

strings.json

{
  "strings": [
    {
      "name": "city",
      "text": "City"
    },
    {
      "name": "phone",
      "text": "Phone"
    },
    {
      "name": "address",
      "text": "Address"
    }
  ]
}

main.py

import json

with open('strings.json') as f:
    d = json.load(f)
    print(d)

We call open with the file path to the JSON file.

Then we call json.load with the opened file.

And then we print d which has the JSON string read from the file.

Therefore, d is:

{'strings': [{'name': 'city', 'text': 'City'}, {'name': 'phone', 'text': 'Phone'}, {'name': 'address', 'text': 'Address'}]}

Since we used the with statement, the file will automatically close once we’re done using it.

Conclusion

To read JSON from a file with Python, we can use the json.loads method.

Categories
Python Answers

How to combine two dicts and add values for keys that appear in both with Python?

Sometimes, we want to combine two dicts and add values for keys that appear in both with Python.

In this article, we’ll look at how to combine two dicts and add values for keys that appear in both with Python.

How to combine two dicts and add values for keys that appear in both with Python?

To combine two dicts and add values for keys that appear in both with Python, we can use the Counter class from the collections module.

For instance, we write:

from collections import Counter
A = Counter({'a':1, 'b':2, 'c':3})
B = Counter({'b':3, 'c':4, 'd':5})
C =  A + B
print(C)

We create Counter instances from 2 dicts and assign them to A and B respectively.

Then we add the values of each dict entry together by using the + operator and assign the result to C.

Therefore, we see that C is Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1}) from what we printed.

Conclusion

To combine two dicts and add values for keys that appear in both with Python, we can use the Counter class from the collections module.