Categories
Python Answers

How to remove duplicate dicts in list in Python?

Sometimes, we want to remove duplicate dicts in list in Python.

In this article, we’ll look at how to remove duplicate dicts in list in Python.

How to remove duplicate dicts in list in Python?

To remove duplicate dicts in list in Python, we can use list comprehension.

For instance, we write:

d = [{'a': 123}, {'b': 123}, {'a': 123}]
no_dups = [i for n, i in enumerate(d) if i not in d[n + 1:]]
print(no_dups)

We have the d list with duplicate dicts.

Then we use not in d[n + 1:] to filter out the dicts that are duplicates of the dict in index i.

And then we assign the resulting list to no_dups.

Therefore, no_dups is:

[{'b': 123}, {'a': 123}]

Conclusion

To remove duplicate dicts in list in Python, we can use list comprehension.

Categories
Python Answers

How to make a timezone aware datetime object in Python?

Sometimes, we want to make a time zone aware datetime object in Python.

In this article, we’ll look at how to make a time zone aware datetime object in Python.

How to make a timezone aware datetime object in Python?

To make a time zone aware datetime object in Python, we can use the pytz module.

For instance, we write:

import datetime
import pytz

unaware = datetime.datetime(2020, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2020, 8, 15, 8, 15, 12, 0, pytz.UTC)

now_aware = pytz.utc.localize(unaware)
assert aware == now_aware

We create datetime objects with the datetime.datetime method.

And as pass in the time zone as the last argument of datetime.datetime to create a UTC datetime.

Without the time zone argument, then datetime object isn’t time zone aware.

To convert a time zone unaware datetime to a time zone aware datetime, we call pytz.utc.localize.

Therefore, aware and non_aware are the same since we made both datetimes time zone aware, have the same time zone, and have the same date and time.

Conclusion

To make a time zone aware datetime object in Python, we can use the pytz module.

Categories
Python Answers

How to format a string in Python?

Sometimes, we want to format a string in Python.

In this article, we’ll look at how to format a string in Python.

How to format a string in Python?

To format a string in Python, we can use the string’s format method.

For instance, we write:

s = "{0}, {1}, {2}".format(1, 2, 3)
print(s)

We call format with the string placeholders separated by commas.

We create placeholders by using integers surrounded by curly braces.

Therefore, s is '1, 2, 3'.

Conclusion

To format a string in Python, we can use the string’s format method.

Categories
Python Answers

How to check for palindromes using Python?

Sometimes, we want to check for palindromes using Python.

In this article, we’ll look at how to check for palindromes using Python.

How to check for palindromes using Python?

To check for palindromes using Python, we can use the Python slice syntax.

For instance, we write:

def is_palindrome(n):
    return str(n) == str(n)[::-1]


print(is_palindrome('abba'))
print(is_palindrome('foobar'))

to create the is_palindrome function that takes a string n and check if the string is the same as is and when it’s reversed.

We reversed n with str(n)[::-1].

Therefore, print should print:

True
False

respectively.

Conclusion

To check for palindromes using Python, we can use the Python slice syntax.

Categories
Python Answers

How to remove punctuation with Python Pandas?

Sometimes, we want to remove punctuation with Python Pandas.

In this article, we’ll look at how to remove punctuation with Python Pandas.

How to remove punctuation with Python Pandas?

To remove punctuation with Python Pandas, we can use the DataFrame’s str.replace method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'text': ['a..b?!??', '%hgh&12', 'abc123!!!', '$$$1234']})
df['text'] = df['text'].str.replace(r'[^\w\s]+', '')

print(df)

We call replace with a regex string that matches all punctuation characters and replace them with empty strings.

Therefore, df is:

import pandas as pd

df = pd.DataFrame({'text': ['a..b?!??', '%hgh&12', 'abc123!!!', '$$$1234']})
df['text'] = df['text'].str.replace(r'[^\w\s]+', '')

print(df)

replace returns a new DataFrame column and we assign that to df['text'].

Therefore, df is:

     text
0      ab
1   hgh12
2  abc123
3    1234

Conclusion

To remove punctuation with Python Pandas, we can use the DataFrame’s str.replace method.