Posted by: xSicKxBot - 10-17-2022, 03:24 AM - Forum: Python
- No Replies
Python TypeError: ‘dict_keys’ Not Subscriptable (Fix This Stupid Bug)
5/5 – (1 vote)
Do you encounter the following error message?
TypeError: 'dict_keys' object is not subscriptable
You’re not alone! This short tutorial will show you why this error occurs, how to fix it, and how to never make the same mistake again.
So, let’s get started!
Solution
Python raises the “TypeError: 'dict_keys' object is not subscriptable” if you use indexing or slicing on the dict_keys object obtained with dict.keys(). To solve the error, convert the dict_keys object to a list such as in list(my_dict.keys())[0].
print(list(my_dict.keys())[0])
Example
The following minimal example that leads to the error:
d = {1:'a', 2:'b', 3:'c'}
print(d.keys()[0])
Output:
Traceback (most recent call last): File "C:\Users\...\code.py", line 2, in <module> print(d.keys()[0])
TypeError: 'dict_keys' object is not subscriptable
Note that the same error message occurs if you use slicing instead of indexing:
d = {1:'a', 2:'b', 3:'c'}
print(d.keys()[:-1]) # <== same error
Fixes
The reason this error occurs is that the dictionary.keys() method returns a dict_keys object that is not subscriptable.
You can use the type() function to check it for yourself:
print(type(d.keys()))
# <class 'dict_keys'>
Note: You cannot expect dictionary keys to be ordered, so using indexing on a non-ordered type wouldn’t make too much sense, would it?
You can fix the non-subscriptable TypeError by converting the non-indexable dict_keys object to an indexable container type such as a list in Python using the list() or tuple() function.
Here’s an example fix:
d = {1:'a', 2:'b', 3:'c'}
print(list(d.keys())[0])
# 1
Here’s an other example fix:
d = {1:'a', 2:'b', 3:'c'}
print(tuple(d.keys())[:-1])
# (1, 2)
Both lists and tuples are subscriptable so you can use indexing and slicing after converting the dict_keys object to a list or a tuple.
Python raises the TypeError: 'dict_keys' object is not subscriptable if you try to index x[i] or slice x[i:j] a dict_keys object.
The dict_keys type is not indexable, i.e., it doesn’t define the __getitem__() method. You can fix it by converting the dictionary keys to a list using the list() built-in function.
Alternatively, you can also fix this by removing the indexing or slicing call, or defining the __getitem__ method. Although the previous approach is often better.
What’s Next?
I hope you’d be able to fix the bug in your code! Before you go, check out our free Python cheat sheets that’ll teach you the basics in Python in minimal time:
If you struggle with indexing in Python, have a look at the following articles on the Finxter blog—especially the third!
Posted by: xSicKxBot - 10-17-2022, 03:24 AM - Forum: Lounge
- No Replies
Call Of Duty Mobile: Zombies Shi No Numa Secret Boss Fight Guide
The latest season has arrived to Call of Duty Mobile, and as the title suggests, Season 9: Zombies Are Back is an update focused on the undead. The Halloween-themed update also brings the return of the classic Shi No Numa Zombies map, which features a hidden boss fight. Here is everything you need to know to unlock the option to complete the Easter egg steps and defeat the boss.
How to unlock Shi No Numa's Easter egg boss
Shi No Numa was briefly featured in Call of Duty Mobile back in 2019, but the classic Zombies map was removed and eventually replaced with the objective-style "Undead Siege" mode. Even if you played Shi No Numa the first time it was introduced into the mobile game, you'll still need to go through these steps to unlock the mode needed to complete the boss fight.
When you first log onto the game and download the Season 9 update, you'll need to do two things in order to unlock the ability to access the mode needed for the Easter egg.
We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.
Once the site of fierce territorial battles, it has since developed into one of the continent's leading trade and financial centers.
However, pressure from the Erebonian Empire and the Calvard Republic is steadily increasing. While corrupt officials from both sides remain locked in political disputes, the mafia and underground criminal organizations are preparing to start a war.
In the midst of all this chaos, the Crossbell Police Department has lost the trust of its people.
Among them are Lloyd Bannings, a rookie agent,
Elie MacDowell, granddaughter of Crossbell's mayor,
Tio Plato, a young sorcereress who wields an orbal staff,
and Randy Orlando, a former security guard.
The foursome are assigned to a new department, the Special Support Section, where they are left with no choice but to join forces in the face of adversity.
This is a story about four unlikely heroes fighting to overcome the walls defining their way of life.
The release date is proposed for September 21, 2017 and it’s time to make sure your code will work with JDK 9. As you probably know, you will still be able to use the classpath and code with any official Java SE APIs and supported JDK-specific APIs. You will run into problems if your code uses certa...
Posted by: xSicKxBot - 10-16-2022, 03:49 AM - Forum: Python
- No Replies
Python – Return NumPy Array From Function
5/5 – (1 vote)
Do you need to create a function that returns a NumPy array but you don’t know how? No worries, in sixty seconds, you’ll know! Go!
A Python function can return any object such as a NumPy Array. To return an array, first create the array object within the function body, assign it to a variable arr, and return it to the caller of the function using the keyword operation “return arr“.
For example, the following code creates a function create_array() of numbers 0, 1, 2, …, 9 using the np.arange() function and returns the array to the caller of the function:
import numpy as np def create_array(): ''' Function to return array ''' return np.arange(10) numbers = create_array()
print(numbers)
# [0 1 2 3 4 5 6 7 8 9]
The np.arange([start,] stop[, step]) function creates a new NumPy array with evenly-spaced integers between start (inclusive) and stop (exclusive).
The step size defines the difference between subsequent values. For example, np.arange(1, 6, 2) creates the NumPy array [1, 3, 5].
To better understand the function, have a look at this video:
I also created this figure to demonstrate how NumPy’s arange() function works on three examples:
In the code example, we used np.arange(10) with default start=0 and step=1 only specifying the stop=10 argument.
If you need an even deeper understanding, I’d recommend you check out our full guide on the Finxter blog.
You can also create a 2D (or multi-dimensional) array in a Python function by first creating a 2D or (xD) nested list and converting the nested list to a NumPy array by passing it into the np.array() function.
The following code snippet uses nested list comprehension to create a 2D NumPy array following a more complicated creation pattern:
import numpy as np def create_array(a,b): ''' Function to return array ''' lst = [[(i+j)**2 for i in range(a)] for j in range(b)] return np.array(lst) arr = create_array(4,3)
print(arr)
Output:
[[ 0 1 4 9] [ 1 4 9 16] [ 4 9 16 25]]
I definitely recommend reading the following tutorial to understand nested list comprehension in Python:
Q: How do you tell an introverted computer scientist from an extroverted computer scientist? A: An extroverted computer scientist looks at your shoes when he talks to you.
❤️ Slain: Back From Hell Store Page[store.epicgames.com]
The games are free to keep if claimed by: Thursday, 13 October 2022 15:00 UTC.
Next week's freebies: ToeJam & Earl: Back in the Groove! Darkwood
We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.
Dome Romantik has grown to become Dome Keeper with beautiful updated pixel art, atmospheric music and sound and more of everything.
Defend your dome from wave after wave of hostile attacks in this roguelike survival miner. Use the time between each attack to dig beneath the surface in search of valuable resources. Use them carefully on powerful upgrades to help you stay alive and make it to the next world.