Quantcast
Channel: Planet Python
Viewing all 23255 articles
Browse latest View live

ItsMyCode: [Solved] AttributeError: ‘str’ object has no attribute ‘get’

$
0
0

The AttributeError: ‘str’ object has no attribute ‘get’ mainly occurs when you try to call the get() method on the string data type. The attribute get() method is present in the dictionary and must be called on the dictionary data type.

In this tutorial, we will look at what exactly is AttributeError: ‘str’ object has no attribute ‘get’ and how to resolve this error with examples.

What is AttributeError: ‘str’ object has no attribute ‘get’?

If we call the get() method on the string data type, Python will raise an AttributeError: ‘str’ object has no attribute ‘get’. The error can also happen if you have a method which returns an string instead of a dictionary.

Let us take a simple example to reproduce this error.

# Method return string instead of dict
def fetch_data():
    output = "Toyota Car"
    return output


data = fetch_data()
print(data.get("name"))

Output

AttributeError: 'str' object has no attribute 'get'

In the above example, we have a method fetch_data() which returns an string instead of a dictionary.

Since we call the get() method on the string type, we get AttributeError.

We can also check if the variable type using the type() method, and using the dir() method, we can also print the list of all the attributes of a given object.

# Method return string instead of dict
def fetch_data():
    output = "Toyota Car"
    return output


data = fetch_data()
print("The type of the object is ", type(data))
print("List of valid attributes in this object is ", dir(data))

Output

The type of the object is  <class 'str'>

List of valid attributes in this object is  ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

How to fix AttributeError: ‘str’ object has no attribute ‘get’?

Let us see how we can resolve the error.

Solution 1 – Call the get() method on valid dictionary

We can resolve the error by calling the get() method on the valid dictionary object instead of the string type.

The dict.get() method returns the value of the given key. The get() method will not throw KeyError if the key is not present; instead, we get the None value or the default value that we pass in the get() method.

# Method returns dict
def fetch_data():
    output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
    return output

data = fetch_data()

# Get the  car Name
print(data.get("Name"))

Output

Audi

Solution 2 – Check if the object is of type dictionary using type

Another way is to check if the object is of type dictionary; we can do that using the type() method. This way, we can check if the object is of the correct data type before calling the get() method.

# Method returns dict
def fetch_data():
    output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
    return output


data = fetch_data()

# Check if the object is dict
if (type(data) == dict):
    print(data.get("Name"))


softwares = "Norton, Bit Defender"

if (type(softwares) == dict):
    print(softwares.get("Name"))
else:
    print("The object is not dictionary and it is of type ", type(softwares))

Output

Audi
The object is not dictionary and it is of type  <class 'str'>

Solution 3 – Check if the object has get attribute using hasattr

Before calling the get() method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr() method, we can check if the object has an attribute with the given name.

# Method returns dict
def fetch_data():
    output = {"Name": "Audi", "Release_Date": "2022", "Price": "$45000"}
    return output


data = fetch_data()

# Check if the object has get attribute
if (hasattr(data, 'get')):
    print(data.get("Name"))

Output

Audi

Conclusion

The AttributeError: ‘str’ object has no attribute ‘get’ occurs when you try to call the get() method on the string data type. The error also occurs if the calling method returns an string instead of a dictionary object.

We can resolve the error by calling the get() method on the dictionary object instead of an string. We can check if the object is of type dictionary using the type() method, and also, we can check if the object has a valid get attribute using hasattr() before performing the get operation.


ItsMyCode: [Solved] AttributeError: ‘NoneType’ object has no attribute ‘get’

$
0
0

The AttributeError: ‘NoneType’ object has no attribute ‘get’ mainly occurs when you try to call the get() method on the None value. The attribute get() method is present in the dictionary and must be called on the dictionary data type.

In this tutorial, we will look at what exactly is AttributeError: ‘NoneType’ object has no attribute ‘get’ and how to resolve this error with examples.

What is AttributeError: ‘NoneType’ object has no attribute ‘get’?

If we call the get() method on the None value, Python will raise an AttributeError: ‘NoneType’ object has no attribute ‘get’. The error can also happen if you have a method which returns an None instead of a dictionary or if we forget the return statement in the function as shown below.

Let us take a simple example to reproduce this error.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}


data = fetch_data()
print(data.get("name"))

Output

AttributeError: 'NoneType' object has no attribute 'get'

In the above example, we have a method fetch_data() which returns an None instead of a dictionary because the return statement is missing.

Since we call the get() method on the None value, we get AttributeError.

We can also check if the variable type using the type() method, and using the dir() method, we can also print the list of all the attributes of a given object.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}


data = fetch_data()
print("The type of the object is ", type(data))
print("List of valid attributes in this object is ", dir(data))

Output

The type of the object is  <class 'NoneType'>

List of valid attributes in this object is  ['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
PS C:\Personal\IJS\Code>

How to fix AttributeError: ‘NoneType’ object has no attribute ‘get’?

Let us see how we can resolve the error.

Solution 1 – Call the get() method on valid dictionary

We can resolve the error by calling the get() method on the valid dictionary object instead of the None type.

The dict.get() method returns the value of the given key. The get() method will not throw KeyError if the key is not present; instead, we get the None value or the default value that we pass in the get() method.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Get the  car Name
print(data.get("name"))

Output

Audi

Solution 2 – Check if the object is of type dictionary using type

Another way is to check if the object is of type dictionary; we can do that using the type() method. This way, we can check if the object is of the correct data type before calling the get() method.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Check if the object is dict
if (type(data) == dict):
    print(data.get("name"))


softwares = None

if (type(softwares) == dict):
    print(softwares.get("name"))
else:
    print("The object is not dictionary and it is of type ", type(softwares))

Output

Audi
The object is not dictionary and it is of type  <class 'NoneType'>

Solution 3 – Check if the object has get attribute using hasattr

Before calling the get() method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr() method, we can check if the object has an attribute with the given name.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Check if the object is dict
if (hasattr(data, 'get')):
    print(data.get("name"))


# Incase of None value
softwares = None

if (hasattr(softwares, 'get')):
    print(softwares.get("name"))
else:
    print("The object does not have get attribute")

Output

Audi
The object does not have get attribute

Conclusion

The AttributeError: ‘NoneType’ object has no attribute ‘get’ occurs when you try to call the get() method on the None type. The error also occurs if the calling method returns an None instead of a dictionary object.

We can resolve the error by calling the get() method on the dictionary object instead of an None. We can check if the object is of type dictionary using the type() method, and also, we can check if the object has a valid get attribute using hasattr() before performing the get operation.

ItsMyCode: [Solved] AttributeError: ‘tuple’ object has no attribute ‘get’

$
0
0

The AttributeError: ‘tuple’ object has no attribute ‘get’ mainly occurs when you try to call the get() method on the tuple value. The attribute get() method is present in the dictionary and must be called on the dictionary data type.

In this tutorial, we will look at what exactly is AttributeError: ‘tuple’ object has no attribute ‘get’ and how to resolve this error with examples.

What is AttributeError: ‘tuple’ object has no attribute ‘get’?

If we call the get() method on the tuple value, Python will raise an AttributeError: ‘tuple’ object has no attribute ‘get’. The error can also happen if you have a method which returns an tuple instead of a dictionary.

Let us take a simple example to reproduce this error.

# Method return None instead of dict
def fetch_data():
    output = ("Audi", "BMW")
    return output


data = fetch_data()
print(data.get("name"))

Output

AttributeError: 'tuple' object has no attribute 'get'

In the above example, we have a method fetch_data() which returns an tuple instead of a dictionary.

Since we call the get() method on the tuple value, we get AttributeError.

We can also check if the variable type using the type() method, and using the dir() method, we can also print the list of all the attributes of a given object.

# Method return None instead of dict
def fetch_data():
    output = ("Audi", "BMW")
    return output


data = fetch_data()
print("The type of the object is ", type(data))
print("List of valid attributes in this object is ", dir(data))

Output

The type of the object is  <class 'tuple'>

List of valid attributes in this object is  ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

How to fix AttributeError: ‘tuple’ object has no attribute ‘get’?

Let us see how we can resolve the error.

Solution 1 – Call the get() method on valid dictionary

We can resolve the error by calling the get() method on the valid dictionary object instead of the tuple type.

The dict.get() method returns the value of the given key. The get() method will not throw KeyError if the key is not present; instead, we get the None value or the default value that we pass in the get() method.

# Method returns dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Get the  car Name
print(data.get("name"))

Output

Audi

Solution 2 – Check if the object is of type dictionary using type

Another way is to check if the object is of type dictionary; we can do that using the type() method. This way, we can check if the object is of the correct data type before calling the get() method.

# Method returns dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Check if the object is dict
if (type(data) == dict):
    print(data.get("name"))


softwares = ("Audi", "BMW")

if (type(softwares) == dict):
    print(softwares.get("name"))
else:
    print("The object is not dictionary and it is of type ", type(softwares))

Output

Audi
The object is not dictionary and it is of type  <class 'tuple'>

Solution 3 – Check if the object has get attribute using hasattr

Before calling the get() method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr() method, we can check if the object has an attribute with the given name.

# Method returns dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Check if the object is dict
if (hasattr(data, 'get')):
    print(data.get("name"))


# Incase of None value
softwares =  ("Audi", "BMW")

if (hasattr(softwares, 'get')):
    print(softwares.get("name"))
else:
    print("The object does not have get attribute")

Output

Audi
The object does not have get attribute

Conclusion

The AttributeError: ‘tuple’ object has no attribute ‘get’ occurs when you try to call the get() method on the None type. The error also occurs if the calling method returns an tuple instead of a dictionary object.

We can resolve the error by calling the get() method on the dictionary object instead of an tuple. We can check if the object is of type dictionary using the type() method, and also, we can check if the object has a valid get attribute using hasattr() before performing the get operation.

Matt Layman: Refactoring and New Features - Building SaaS with Python and Django #137

$
0
0
In this episode, I continued on the teacher checklist for the homeschooling app. We added data to the context and this required some refactoring to be able to reuse data from other parts of the app.

PyCharm: Webinar Recording: “Idiomatic Pandas: 5 tips for better Pandas”, With Matt Harrison

PyCharm

$
0
0

On Tuesday, June 21, 2022, Matt Harrison joined Jodie Burchell for a webinar about Pandas, and how to be more effective while working with this popular library. Here’s the recording for you to watch if you missed the live stream.

Description

In this webinar Matt Harrison and Jodie Burchell discussed tips for making Pandas more memory-friendly, getting the best performance possible when applying operations to Series and DataFrames, keeping your Pandas code as reproducible and tidy as possible, and how using the right tooling can make working with Pandas easier. They discussed how to deal with trickier topics in data processing such as feature engineering and missing data. Finally, they talked about some user-submitted tips which help get the best out of Pandas.

Speaking to You

Matt Harrison runs MetaSnake, a Python and Data Science consultancy and corporate training shop. In the past, he has worked across the domains of search, build management and testing, business intelligence, and storage. He has presented and taught tutorials at conferences such as Strata, SciPy, SCALE, PyCON, and OSCON, as well as local user conferences. He has written a number of books on Python and Data Science, including Machine Learning Pocket ReferencePandas 1.x CookbookEffective PyCharm, and Effective Pandas. He blogs at hairysun.com.

Dr. Jodie Burchell is a Developer Advocate for Data Science at JetBrains and was previously the Lead Data Scientist in audiences generation at Verve Group Europe. After finishing a PhD in psychology and a postdoc in biostatistics, she has worked in a range of data science and machine learning roles across search improvement, recommendation systems, natural language processing, and programmatic advertising. She is also the author of two books, The Hitchhiker’s Guide to Ggplot2 and The Hitchhiker’s Guide to Plotnine, and blogs at t-redactyl.io.

Mike Driscoll: An Intro to Kivy Layouts (Video)

PyBites: Common Python developer pitfalls and the 80/20 that really matters

$
0
0

Listen here:

Welcome back to another Pybites podcast episode. In this episode we talk about common pitfalls you want to avoid when becoming a Python developer:

Pitfall #1: Tutorial paralysis
Pitfall #2: Improper sequencing
Pitfall #3: Obsessing over Pythonic code
Pitfall #4: Going on your own for too long

… after that we look at the 80/20 (aka “Pareto”) to focus on  to become a well-rounded Python developer:

80/20 Rule #1: Work on bigger projects
80/20 Rule #2: Build a portfolio
80/20 Rule #3: Work with experienced developers
80/20 Rule #4: Become a content provider


If this resonates with you and you want to better your career as a Pythonista, book us in for a career chathttps://go.oncehub.com/pybites

Thanks for listening,  Any feedback, write us an email to info@pybit.es

We’ll be back next week!


Real Python: The Real Python Podcast – Episode #115: Digging Into PyScript & Preventing or Handling Python Errors

$
0
0

Have you heard about PyScript? The brand-new framework has the community excited about building interactive Python applications that run entirely within the user's browser. Would you like to dig into the details beyond the "Hello World" examples? This week on the show, Christopher Trudeau is here, bringing another batch of PyCoder's Weekly articles and projects.


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Zero to Mastery: Python Monthly Newsletter 💻🐍

$
0
0
31st issue of the Python Monthly Newsletter! Read by 25,000+ Python developers every month. This monthly Python newsletter covers the latest Python news so that you stay up-to-date with the industry and keep your skills sharp.

Robin Wilson: Update: recent work, conference talks and 3D printers

$
0
0

It’s been just over a year since I last posted here – and it’s been a busy year.

I’m aiming to start posting a bit more frequently (though I’ve said that before…), so I thought I’d start with an update of what I’ve been up to since my last post.

Work

Last October I started a new contract with Anglo American, a global mining and minerals company. They brought me in to work develop a new system called Image Hub, which will provide a central place to store, search, visualise and process image data. We’re focusing mainly on satellite and aerial images at the moment, but will be expanding to other sorts of geospatial and non-geospatial in the future.

I started as part of a very small team (me and one other person), evaluating a range of technologies to solve this problem. We then progressed to building some prototypes, and now have an initial working system in pre-production. We’re starting to get more people on the team and are working towards getting a full system in production.

I’ve really enjoyed getting stuck into the Cloud Native Geospatial ecosystem – including Spatio-Temporal Asset Catalogs, Cloud-Optimized GeoTIFFs and the various associated technologies. I’d used these before as a data consumer, but now I’ve been on the other side, setting up STAC API servers, converting data to COGs. setting up Tilers.

I attended the Cloud Native Geospatial Day 2022 and gave a talk on our work at Anglo, which you can watch below:

Although my work with Anglo is taking most of my time, I’ve kept going with a bit of other work including some consulting on Py6S.

Electromagnetic Field

I attended Electromagnetic Field with my family during the May half-term. EMF is a science/technology/electronics/computing/general-geek festival held in a field in Herefordshire. We camped there (the first time my son had been camping) and had a wonderful time.

I did a couple of workshops where I built a Z80-based computer and a Geiger counter and my wife did some soldering workshops and a blacksmithing workshop. My son (only 5 years old) even made and launched a solid-fuelled rocket!

As well as all the workshops there were some fascinating talks – and I also gave a talk titled Learning from accidents: an introduction to railway signalling in the UK. It was heavily based on one of the talks that I give to science/technology societies (see my talks page) but extended and altered a bit for the EMF audience. All the talks were videoed, so I’ll post a link here when the video is available.

Fun evening activities

Since coming back from EMF I’ve been inspired to do some interesting things in the evenings. This is partly because a friend gave me a 3D printer at EMF, so I’ve been having fun getting to grips with that. I’ve also had fun using the things I made in the workshops at EMF. Some of the things I’ve been up to include:

  • Designing (using Fusion 360) and 3D printing a mini balloon-powered hovercraft
  • Printing a load of cool 3D prints from sites like Thingiverse
  • Connecting my Geiger counter (from EMF) to a Raspberry Pi (and later to an Arduino, and the EMF badge) to get count data out, and to generate true random numbers
  • Writing programs in Z80 assembler (just like my father did many years ago) – which has been fascinating, and a nice change from the modern ‘wire all these APIs together and try and work out which dependency has a bug that’s causing your problem’ approach to programming

I’m hoping to write some posts here on some of these activities – stay tuned to hear more…

Mike Driscoll: Using Python to Turn Text-to-Speech on Mac OSX (Video)

Django Weblog: PyCharm &amp; DSF Campaign 2022 Results

$
0
0

The sixth annual JetBrains PyCharm promotion in June netted the Django Software Foundation $25,000 this year.

This amount represents over 10% of the DSF's overall budget, which goes directly into funding the continued development and support of Django via the Django Fellowship program and Django conferences worldwide.

Django Software Foundation

The Django Software Foundation is the non-profit foundation that supports the development of the Django Web framework. It funds the Django Fellowship program, which currently supports two Fellows who triage tickets, review/merge patches from the community, and work on infrastructure. The introduction of this program starting in 2015 has gone a long way towards ensuring a consistent major release cycle and the fixing/blocking of severe bugs. DSF also funds development sprints, community events like DjangoCons, and related conferences and workshops globally.

Fundraising is still ongoing and you can donate directly at djangoproject.com/fundraising.

Python for Beginners: List of Dictionaries to Dataframe in Python

$
0
0

Dataframes are mainly used in python for the analysis of tabular data. In this article, we will discuss how we can convert a list of dictionaries to a dataframe in python.

List of Dictionaries to Dataframe Using pandas.DataFrame()

The dataframe objects are defined in the pandas module. To create a dataframe from a given list of dictionaries, we can use the DataFrame() method. The DataFrame() method object takes a list of dictionaries as input argument and returns a dataframe created from the dictionaries. Here, the column names for the dataframe consist of the keys in the python dictionary. The values of each dictionary are transformed into the rows of the dataframe. You can create a dataframe from a list of dictionaries using the pandas.DataFrame() method as follows.

import pandas as pd

listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
              {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
df = pd.DataFrame(listOfDict)
print("The dataframe is:")
print(df)

Output:

THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The dataframe is:
     Name  Roll    Language
0  Aditya     1      Python
1     Sam     2        Java
2   Chris     3         C++
3    Joel     4  TypeScript

In the dataframe, a column is created for each key in the list of dictionaries. If a dictionary doesn’t have any specific key, the value NaN is given to the column corresponding to the specific key in the row representing the dictionary.

List of Dictionaries to Dataframe in Python Using pandas.dataframe.from_dict() Method

Instead of using the DataFrame() method, we can also use the from_dict() method to convert a list of dictionaries to a dataframe in Python. The from_dict() method takes a list of dictionaries as its input argument and returns a dataframe. Again, the column names for the dataframe consist of the keys in the dictionary. The values of each dictionary are transformed into the rows of the dataframe. You can create a dataframe from a list of dictionaries using the from_dict() method as follows.

import pandas as pd

listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
              {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
df = pd.DataFrame.from_dict(listOfDict)
print("The dataframe is:")
print(df)

Output:

THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The dataframe is:
     Name  Roll    Language
0  Aditya     1      Python
1     Sam     2        Java
2   Chris     3         C++
3    Joel     4  TypeScript

You can observe that the dataframe generated by the from_dict() method is similar to the dataframe generated by the DataFrame() method.

List of Dictionaries to Dataframe Using pandas.dataframe.from_records(Data)

To create a dataframe from a list of dictionaries in Python, we can also use the from_records() method. The from_records() method takes a list of dictionaries as its input argument and returns a dataframe. Again, the column names for the dataframe consist of the keys in the dictionary. The values of each dictionary are transformed into the rows of the dataframe. You can create a dataframe from a list of dictionaries using the from_records() method as follows.

import pandas as pd

listOfDict = [{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'},
              {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
print("THe list of dictionaries is:")
print(listOfDict)
df = pd.DataFrame.from_records(listOfDict)
print("The dataframe is:")
print(df)

Output:

THe list of dictionaries is:
[{'Name': 'Aditya', 'Roll': 1, 'Language': 'Python'}, {'Name': 'Sam', 'Roll': 2, 'Language': 'Java'}, {'Name': 'Chris', 'Roll': 3, 'Language': 'C++'}, {'Name': 'Joel', 'Roll': 4, 'Language': 'TypeScript'}]
The dataframe is:
     Name  Roll    Language
0  Aditya     1      Python
1     Sam     2        Java
2   Chris     3         C++
3    Joel     4  TypeScript

Conclusion

In this article, we have discussed three ways to convert a list of dictionaries to a dataframe in python. All three methods are semantically similar and produce the same result. To learn more about dictionaries, you can read this article on dictionary comprehension in python. You might also like this article on list comprehension in python.

The post List of Dictionaries to Dataframe in Python appeared first on PythonForBeginners.com.

ItsMyCode: [Solved] AttributeError: module ‘time’ has no attribute ‘clock’

$
0
0

The time.clock() method has been removed in Python 3.8 onwards. Hence if you are using the clock() method in Python 3.8 or above, you will get AttributeError: module ‘time’ has no attribute ‘clock’.  

In this tutorial, we will look into what exactly is AttributeError: module ‘time’ has no attribute ‘clock’ and how to resolve the error with examples.

What is AttributeError: module ‘time’ has no attribute ‘clock’?

The time.clock() method has been deprecated from Python 3.8 onwards, which leads to an AttributeError: module ‘time’ has no attribute ‘clock’ if used in the code.

If you are not using the clock() method but still facing this error, that means you are using some of the Python libraries such as PyCryptosqlalchemy, etc., that internally use time.clock() method.

Let us try to reproduce the error in Python 3.8

import time

print(time.clock())

Output

AttributeError: module 'time' has no attribute 'clock'

How to fix AttributeError: module ‘time’ has no attribute ‘clock’?

There are multiple solutions to resolve this AttributeError and the solution depends on the different use cases. Let us take a look at each scenario.

Solution 1 – Replace time.clock() with time.process_time() and time.perf_counter()

Instead of the time.clock() method, we can use an alternate methods such as time.perf_counter() and time.process_time() that provides the same results.

Let us take an example to see how this can be implemented.

The time.perf_counter() function returns a float value of time in seconds i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. 

import time

# perf_counter includes the execution time and the sleep time
start_time = time.perf_counter()
time.sleep(4)
end_time = time.perf_counter()

print("Elapsed Time is ", end_time-start_time)

Output

Elapsed Time is  4.0122200999903725

The time.process_time() method will return a float value of time in seconds. The time returned would be the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. 

import time

# perf_counter includes the execution time and the sleep time
start_time = time.process_time()
for i in range(1000):
    print(i, end=' ')
end_time = time.process_time()

print("Elapsed Time is ", end_time-start_time)

Output

Elapsed Time is  0.015625

Solution 2- Upgrade the module to the latest version

If you are directly using the time.clock() method in your code, then some of the external modules that you are using would be using it internally, and hence you are getting this error.

If you use a module like SQLAlchemy, upgrade it to the latest version using the below command.

pip install <module_name> --upgrade
pip install SQLAlchemy --upgrade

Solution 3 – Replace the module with another alternate

If you are using the modules like PyCrypto, there is no way you can upgrade it as it is not maintained actively.

In this case, you need to look for an alternate module like  PyCryptodome that supports the same functionality. 

# Uninstall the PyCrypto as its not maintained and install pycryptodome 
pip3 uninstall PyCrypto 
pip3 install pycryptodome 

Solution 4 – Downgrade the Python version

It is not a recommended approach to downgrade Python. However, if you have recently upgraded the Python version to 3.8 or above and facing this issue, it is better to revert or downgrade it back to the previous version until you find a solution or implement any of the above solutions.

Conclusion

The AttributeError: module ‘time’ has no attribute ‘clock’ occurs if you are using the time.clock() method in the Python 3.8 or above version. Another reason could be that you are using an external module that internally uses time.clock() function.

We can resolve the issue by using alternate methods such as time.process_time() and time.perf_counter() methods. If the issue is caused due to external modules, it is better to upgrade the module or find an alternative module if the module provides no fix.


Podcast.__init__: Design Real-World Objects In Python With CadQuery

$
0
0
Virtually everything that you interact with on a daily basis and many other things that make modern life possible were designed and modeled in software called CAD or Computer-Aided Design. These programs are advanced suites with graphical editing environments tailored to domain experts in areas such as mechanical engineering, electrical engineering, architecture, etc. While the UI-driven workflow is more accessible, it isn't scalable which opens the door to code-driven workflows. In this episode Jeremy Wright discusses the design, uses, and benefits of the CadQuery framework for building 3D CAD models entirely in Python.

Summary

Virtually everything that you interact with on a daily basis and many other things that make modern life possible were designed and modeled in software called CAD or Computer-Aided Design. These programs are advanced suites with graphical editing environments tailored to domain experts in areas such as mechanical engineering, electrical engineering, architecture, etc. While the UI-driven workflow is more accessible, it isn’t scalable which opens the door to code-driven workflows. In this episode Jeremy Wright discusses the design, uses, and benefits of the CadQuery framework for building 3D CAD models entirely in Python.

Announcements

  • Hello and welcome to Podcast.__init__, the podcast about Python’s role in data and science.
  • When you’re ready to launch your next app or want to try a project you hear about on the show, you’ll need somewhere to deploy it, so take a look at our friends over at Linode. With their managed Kubernetes platform it’s easy to get started with the next generation of deployment and scaling, powered by the battle tested Linode platform, including simple pricing, node balancers, 40Gbit networking, dedicated CPU and GPU instances, and worldwide data centers. And now you can launch a managed MySQL, Postgres, or Mongo database cluster in minutes to keep your critical data safe with automated backups and failover. Go to pythonpodcast.com/linode and get a $100 credit to try out a Kubernetes cluster of your own. And don’t forget to thank them for their continued support of this show!
  • So now your modern data stack is set up. How is everyone going to find the data they need, and understand it? Select Star is a data discovery platform that automatically analyzes & documents your data. For every table in Select Star, you can find out where the data originated, which dashboards are built on top of it, who’s using it in the company, and how they’re using it, all the way down to the SQL queries. Best of all, it’s simple to set up, and easy for both engineering and operations teams to use. With Select Star’s data catalog, a single source of truth for your data is built in minutes, even across thousands of datasets. Try it out for free and double the length of your free trial today at pythonpodcast.com/selectstar. You’ll also get a swag package when you continue on a paid plan.
  • Need to automate your Python code in the cloud? Want to avoid the hassle of setting up and maintaining infrastructure? Shipyard is the premier orchestration platform built to help you quickly launch, monitor, and share python workflows in a matter of minutes with 0 changes to your code. Shipyard provides powerful features like webhooks, error-handling, monitoring, automatic containerization, syncing with Github, and more. Plus, it comes with over 70 open-source, low-code templates to help you quickly build solutions with the tools you already use. Go to dataengineeringpodcast.com/shipyard to get started automating with a free developer plan today!
  • Your host as usual is Tobias Macey and today I’m interviewing Jeremy Wright about CadQuery, an easy-to-use Python module for building parametric 3D CAD models

Interview

  • Introductions
  • How did you get introduced to Python?
  • Can you start by explaining what CAD is and some of the real-world applications of it?
  • Can you describe what CadQuery is and the story behind it?
    • How did you get involved with it and what keeps you motivated?
    • What are the different methods that are in common use for building CAD models?
    • Are there approaches that are more common for models used in different industries?
  • What was missing in other projects for programmatically generating CAD models that motivated you to build CadQuery?
  • Can you describe how the CadQuery library is implemented?
    • How have the design and goals of the project changed or evolved since you started working on it?
    • How would you characterize the rate of change/evolution in the CAD ecosystem, and how has that factored into your work on CadQuery?
  • How did you approach the process of API design?
    • How do you balance accessibility for non-professionals with domain-related nomenclature?
  • Can you describe some example workflows for going from idea to finished product with CadQuery?
  • How are you using CadQuery in your own work?
  • What are the most interesting, innovative, or unexpected ways that you have seen CadQuery used?
  • What are the most interesting, unexpected, or challenging lessons that you have learned while working on CadQuery?
  • When is CadQuery the wrong choice?
  • What do you have planned for the future of CadQuery?

Keep In Touch

Picks

Closing Announcements

  • Thank you for listening! Don’t forget to check out our other shows. The Data Engineering Podcast covers the latest on modern data management. The Machine Learning Podcast helps you go from idea to production with machine learning.
  • Visit the site to subscribe to the show, sign up for the mailing list, and read the show notes.
  • If you’ve learned something or tried out a project from the show then tell us about it! Email hosts@podcastinit.com) with your story.
  • To help other people find the show please leave a review on iTunes and tell your friends and co-workers

Links

The intro and outro music is from Requiem for a Fish The Freak Fandango Orchestra / CC BY-SA

Python Software Foundation: The PSF Board Election is Open!

$
0
0

It’s time to cast your vote! Voting takes place from Monday, June 20 AoE, through Thursday, June 30, 2022 AoE. Check here to see how much time you have left to vote. If you are a voting member of the PSF, you will get an email from “Helios Voting Bot <no-reply@mail.heliosvoting.org>” with your ballot, subject line will read “Vote: Python Software Foundation Board of Directors Election 2022”. If you haven’t seen your ballot by Tuesday, please 1) check your spam folder for a message from “no-reply@mail.heliosvoting.org” and if you don’t see anything 2) get in touch by emailing psf-elections@python.org so we can make sure we have the most up to date email for you.

This might be the largest number of nominees we’ve ever had! Make sure you schedule some time to look at all their statements. We’re overwhelmed by how many of you are willing to contribute to the Python community by serving on the PSF board.

Who can vote? You need to be a Contributing, Managing, Supporting, or Fellow member as of June 15, 2022 to vote in this election. Read more about our membership types here or if you have questions about your membership status please email psf-elections@python.org

#toc, .toc, .mw-warning { border: 1px solid #aaa; background-color: #f9f9f9; padding: 5px; font-size: 95%; }#toc h2, .toc h2 { display: inline; border: none; padding: 0; font-size: 100%; font-weight: bold; }#toc #toctitle, .toc #toctitle, #toc .toctitle, .toc .toctitle { text-align: center; }#toc ul, .toc ul { list-style-type: none; list-style-image: none; margin-left: 0; padding-left: 0; text-align: left; }#toc ul ul, .toc ul ul { margin: 0 0 0 2em; }#toc .toctoggle, .toc .toctoggle { font-size: 94%; }p, h1, h2, h3, li { }body{ padding-top : 1in; padding-bottom : 1in; padding-left : 1in; padding-right : 1in; }

Mike Driscoll: PyDev of the Week: Luiz Gustavo Martins

$
0
0

This week we welcome Luiz Gustavo Martins (@gusthema) as our PyDev of the Week! Luiz has been posting a lot of Python content on Twitter lately, so if you like to learn Python or machine learning, you should check him out.

Let's spend some time getting to know Luiz better!

Can you tell us a little about yourself (hobbies, education, etc):

I'm a Gus and work as Developer Advocate at Google AI. I've been developing systems for 22 years now! As a hobby, I do Capoeira (I've been doing this for +25 years) and tumbling. I also like to build legos and play video games.

Why did you start using Python?

I've been working a lot on how to make using Machine Learning models easy and how to customize them for your application. Some of it you can see here and here

Which Python libraries are your favorite (core or 3rd party)?

TensorFlow!!!! but of course: NumPy, Pandas, matplotlib. I also like the collection built-in lib

How did you decide to get into content creation?

As a developer advocate that's something that I wanted to improve. I already did blog posts and videos but I wanted to increase my reach on social and that's why I'm active now

What are the top 3 things that you find your followers have trouble understanding?

This varies but the content people like is best practices when writing Python code, how to use Pandas effectively and also how to use ML on their applications

Is there anything else you’d like to say?

Python is great and if you'd like some daily content with a Machine Learning perspective, just follow me on Twitter @gusthema

Thanks for doing the interview, Luiz!

The post PyDev of the Week: Luiz Gustavo Martins appeared first on Mouse Vs Python.

Python for Beginners: Insert New Column Into a Dataframe in Python

$
0
0

Dataframes are often used to handle tabular data in python. In this article, we will discuss how we can insert a new column into a dataframe in python.

Insert New Column Into a Dataframe by Indexing in Python

To add a new column into a dataframe, we can use indexing in the same way we add a key-value pair in a python dictionary. In this approach, we will first put all the elements of the column that needs to be inserted into a list. After that, we will add the list as a new column into the dataframe using the following syntax.

datframe_name[column_name]= element_list

Here, 

  • datframe_name is the name of the dataframe into which the column has to be inserted.
  • column_name represents an string that contains the name of the new column.
  • element_list  denotes list containing the elements that will be inserted to the dataframe.

Following is the python source code to insert a new column into a dataframe by indexing.

import pandas as pd

df = pd.read_csv('Demo.csv')
print("The dataframe before inserting the column:")
print(df)
column_data = [180, 164, 170]
df['Height'] = column_data
print("The dataframe after inserting the column:")
print(df)

Output:

The dataframe before inserting the column:
   Roll    Name Language
0     1  Aditya   Python
1     2     Sam     Java
2     3   Chris      C++
The dataframe after inserting the column:
   Roll    Name Language  Height
0     1  Aditya   Python     180
1     2     Sam     Java     164
2     3   Chris      C++     170

Insert New Column Into a Dataframe Using the assign() Method

Instead of using indexing, we can use the assign() method to add a new column into the dataframe. The assign() method, when invoked on a dataframe, takes the column name and the list of elements of the new column as a keyword argument using the following syntax.

datframe_name.assign(column_name= element_list)

Here,

  • datframe_name is the name of the dataframe into which the column has to be inserted.
  • column_name denotes the name of the new column.
  • element_list  is the list containing the elements that will be inserted to the dataframe.

After execution, the assign() method inserts the column into the dataframe and returns the updated dataframe as shown below.

import pandas as pd

df = pd.read_csv('Demo.csv')
print("The dataframe before inserting the column:")
print(df)
column_data = [180, 164, 170]
df = df.assign(Height=column_data)
print("The dataframe after inserting the column:")
print(df)

Output:

The dataframe before inserting the column:
   Roll    Name Language
0     1  Aditya   Python
1     2     Sam     Java
2     3   Chris      C++
The dataframe after inserting the column:
   Roll    Name Language  Height
0     1  Aditya   Python     180
1     2     Sam     Java     164
2     3   Chris      C++     170

The above approaches are used to insert the new column at the end. We can also insert new columns at any position in the dataframe. For that, we can use the insert() method.

Insert New Column Into a Dataframe Using the insert() Method

With the insert() method, we can insert a new column at any position in the dataframe. The insert() method, when invoked on a dataframe, takes the position at which the new column will be inserted as its first input argument, the name of the new column as the second input argument, the list containing the elements of the new column as the third input argument. After execution, it inserts the column at the specified position in the dataframe. You can observe this in the following example.

import pandas as pd

df = pd.read_csv('Demo.csv')
print("The dataframe before inserting the column:")
print(df)
column_data = [180, 164, 170]
df.insert(1, 'Height', column_data)
print("The dataframe after inserting the column:")
print(df)

Output:

The dataframe before inserting the column:
   Roll    Name Language
0     1  Aditya   Python
1     2     Sam     Java
2     3   Chris      C++
The dataframe after inserting the column:
   Roll  Height    Name Language
0     1     180  Aditya   Python
1     2     164     Sam     Java
2     3     170   Chris      C++

Conclusion

In this article, we have discussed three approaches to insert a new column into a dataframe in python. To know more about python programming, you can read this article on list comprehension in python. You might also like this article on dictionary comprehension in python.

The post Insert New Column Into a Dataframe in Python appeared first on PythonForBeginners.com.

Real Python: Build a Tic-Tac-Toe Game With Python and Tkinter

$
0
0

Playing computer games is a great way to unwind or challenge yourself. Some people even do it professionally. It’s also fun and educational to build your own computer games. In this tutorial, you’ll build a classic tic-tac-toe game using Python and Tkinter.

With this project, you’ll go through the thought processes required for creating your own game. You’ll also learn how to integrate your diverse programming skills and knowledge to develop a functional and fun computer game.

In this tutorial, you’ll learn how to:

  • Program the classic tic-tac-toe game’s logic using Python
  • Create the game’s graphical user interface (GUI) using the Tkinter tool kit
  • Integrate the game’s logic and GUI into a fully functional computer game

As mentioned, you’ll be using the Tkinter GUI framework from the Python standard library to create your game’s interface. You’ll also use the model-view-controller pattern and an object-oriented approach to organize your code. For more on these concepts, check out the links in the prerequisites.

To download the entire source code for this project, click the link in the box below:

Get Source Code:Click here to get access to the source code that you’ll use to build your tic-tac-toe game.

Demo: A Tic-Tac-Toe Game in Python

In this step-by-step project, you’ll build a tic-tac-toe game in Python. You’ll use the Tkinter tool kit from the Python standard library to create the game’s GUI. In the following demo video, you’ll get a sense of how your game will work once you’ve completed this tutorial:

Your tic-tac-toe game will have an interface that reproduces the classic three-by-three game board. The players will take turns making their moves on a shared device. The game display at the top of the window will show the name of the player who gets to go next.

If a player wins, then the game display will show a winning message with the player’s name or mark (X or O). At the same time, the winning combination of cells will be highlighted on the board.

Finally, the game’s File menu will have options to reset the game if you want to play again or to exit the game when you’re done playing.

If this sounds like a fun project to you, then read on to get started!

Project Overview

Your goal with this project is to create a tic-tac-toe game in Python. For the game interface, you’ll use the Tkinter GUI tool kit, which comes in the standard Python installation as an included battery.

The tic-tac-toe game is for two players. One player plays X and the other plays O. The players take turns placing their marks on a grid of three-by-three cells. If a given player gets three marks in a row horizontally, vertically, or diagonally, then that player wins the game. The game will be tied if no one gets three in a row by the time all the cells are marked.

With these rules in mind, you’ll need to put together the following game components:

  • The game’s board, which you’ll build with a class called TicTacToeBoard
  • The game’s logic, which you’ll manage using a class called TicTacToeGame

The game board will work as a mix between view and controller in a model-view-controller design. To build the board, you’ll use a Tkinter window, which you can create by instantiating the tkinter.Tk class. This window will have two main components:

  1. Top display: Shows information about the game’s status
  2. Grid of cells: Represents previous moves and available spaces or cells

You’ll create the game display using a tkinter.Label widget, which allows you to display text and images.

For the grid of cells, you’ll use a series of tkinter.Button widgets arranged in a grid. When a player clicks one of these buttons, the game logic will run to process the player’s move and determine whether there’s a winner. In this case, the game logic will work as the model, which will manage the data, logic, and rules of your game.

Now that you have a general idea of how to build your tic-tac-toe game, you should check out a few knowledge prerequisites that’ll allow you to get the most out of this tutorial.

Prerequisites

Read the full article at https://realpython.com/tic-tac-toe-python/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Viewing all 23255 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>