How to Fix Cannot find module ‘typescript’ Error in TypeScript

How to Fix Cannot find module 'typescript' Error in TypeScript

To resolve the cannot find module ‘typescript’ error, run the npm i -g typescript command and build a symbolic link from the globally installed package to node_modules using the npm link typescript command.

Open a terminal in the root directory of your project and run the following commands:

Shell ( Command 1):

// It is use install typescript globally
npm i -g typescript

Output:

added 1 package, and audited 2 packages in 4s
found 0 vulnerabilities

Shell (Command 2):

// To Create an symbolic link from the global typescript package to the node modules of the current folder use below command
npm link typescript

The error should be fixed when you run the above two commands.

If the global TypeScript installation fails, you may need to run the command with sudo.

Run the following command to see if TypeScript has been successfully installed:

shell

tsc --version

The command’s output should show the version of the TypeScript package installed on your machine, for example, 4.8.0.

The npm link command builds a symbolic link from the globally installed package to the current folder’s

node_ modules/ directory.

If the error still persists, try deleting your node_modules and package-lock.json files, re-running npm install, and restart your IDE.

shell:

// The below command is to remove the node_modules and package-lock.json
rm -rf node_modules package-lock.json
// It is use install typescript globally
npm install
// To Create an symbolic link from the global typescript package to the node modules of the current folder use below command
npm link typescript

If the error still continues, be sure to restart your IDE. VSCode frequently crashes, and a reboot occasionally fixes the problem.

NOTE:

If this fails, try installing TypeScript locally.

shell:

// the below command is used to install the typescript and save it on the system
npm install --save-dev typescript

This will add typescript to your project’s development dependencies, eliminating the need to run the link command.

How to Fix Cannot find module ‘X’ Error in TypeScript?

How to Fix Cannot find module 'X' Error in TypeScript

When TypeScript cannot find a third-party or local module in our project, the "Cannot find module or its matching type declarations" error occurs.

To resolve the error, ensure that the module is installed and that moduleResolution is set to node in your tsconfig.json file.

Check that you have the module installed if it is a third-party module.

shell

// install the required module using the npm install command
npm install module-name
// here it saves the module
npm install --save-dev @types/module-name

NOTE:

In your error message, replace module-name with the name of the module.

If you’re encountering issues with a third-party module, try removing your node-modules and package-lock.json files, re-run npm install, and reload your IDE.

shell:

// remove the node modules using the rd and rm commands and also from package-lock.json
rm -rf node_modules package-lock.json
// run npm install command to install all the modules which are in the package.json
npm install

Reload your IDE, VSCode frequently malfunctions/glitches and requires a reboot.

If it doesn’t work or TypeScript can’t find your local modules, try to set moduleResolution in your tsconfig.json file to node.

tsconfig.json

{
  "compilerOptions": {
    "moduleResolution": "node",
    // rest of lines
  }
}

More information regarding classic vs node module resolution can be found in the TypeScript documentation.

If it doesn’t work, make sure TypeScript is tracking the module you’re attempting to import. It should be included in your include array and not in your exclude array in your tsconfig.json file.

tsconfig.json

{
  "compilerOptions": {
    // ...
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "src/**/*.spec.ts"]
}

TypeScript will not be able to find the module if it is not in the src directory when using the configuration from the code snippet above.

Check to see that you haven’t already excluded the module by adding it to your exclude array.

If the error message changes to "Could not find declaration file for module'module-name,'” TypeScript has found the module you are attempting to import but cannot locate its type declarations.

 

How to Fix ReferenceError: exports is not defined in TypeScript?

How to Fix ReferenceError exports is not defined in TypeScript

To fix the "Uncaught ReferenceError: exports is not defined" error, add a script tag that declares/defines an exports variable, such as <script> var exports ={} ;</script>above your JS script tag if in the browser, or remove the type attribute if it is set to the module in your package.json file in Node.js.

Fixing ReferenceError: exports is not defined in TypeScript?

Browser – ReferenceError: exports is not defined

If you see the error when running code in the browser, try to define a global exports variable above the script tags that load your JavaScript files.

index.html

<script>var exports = {};</script>

<!-- Add the JavaScript script below -->
<script src="index.js"></script>

This will define the exports variable and set it to an empty object, preventing an error from occurring if properties are accessed on it.

Browsers do not support the CommonJS syntax of require and module.exports (without using a tool like webpack), which is creating an error.

If you’re testing your code in the browser, remove the module property from your tsconfig.json file and change the target to es6.

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",  // change the targe to es6
    // "module": "commonjs", // Remove this or comment it (if browser env)
  }
}

When you remove the module option and set the target to es6, the imports and exports of your ES6 modules will not be compiled to the older CommonJS syntax that browsers do not support.

Because modern browsers support all ES6 features, ES6 is a suitable choice.

If it doesn’t work, try to set the type attribute to module in your script tags.

index.html

<!-- Set the correct path according to the setup --> 
<script type="module" src="index.js"></script>

And use the ES6 Modules syntax to import and export.

index.ts

import {v4} from 'uuid'
// Create a function which does the product of two arguments provided
export function multiply(a, b) {
  return a * b;
}

Because browsers do not support the CommonJS syntax, setting the module to commonjs in your tsconfig.json instructs TypeScript to emit CommonJS files, which is a very likely cause of the issue.

If you see the error in a Node.js application, consider removing the type attribute from your package.json file if it is set to module.

{
  "type": "module", // remove this liine or comment it
}

When type is set to module, we can no longer use CommonJS’s exports and require syntax and must instead use ES Modules syntax for all imports and exports, which may be causing the error.

This occurs when your package.json file has type set to module but your tsconfig.json file has module set to commonjs.

Because type = module instructs Node.js to utilise ES Modules syntax, while module = commonjs encourages TypeScript to produce CommonJS files, these two options are incompatible.

Examine your tsconfig.json file and make sure it looks like this.

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "esModuleInterop": true,
    "moduleResolution": "node",
    // ... your other options
  }
}

Your target option should be es6 or higher, and your module should be CommonJS.

For imports and exports, make sure to utilize the ES6 modules syntax.

index.ts

import {myDefinedFunction} from './myFile'

export function multiply(a:number, b:number) {
  return a * b;
}

Because Node JS supports the CommonJS syntax, if you use the ES modules syntax and instruct TypeScript to produce CommonJS code by setting module to commonjs, the export above will be compiled to CommonJS and should work.

The only reason it wouldn’t work is that you’re emitting CommonJS files but instructing Node.js to read them using ES6 Module syntax.

 

How to Fix ReferenceError require is not defined in JavaScript?

How to Fix ReferenceError require is not defined in JavaScript

The “ReferenceError: require is not defined” error can arise for several reasons:

  • When we use the require() function in a browser environment.
  • When we use the require() function in a Node.js project, where type is set to module in the package.json file.
  • When we use the require() function in Node.js, where files have a .mjs extension.

Fixing the ReferenceError require is not defined in JavaScript

Use the ES6 module import and export syntax to resolve the “ReferenceError need is not defined” error.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <!-- Write your HTML elements here  -->

    <!-- adding type as module in the script   -->
    <script type="module" src="index.js"></script>
    <script type="module" src="anotherFile.js"></script>
  </body>
</html>
  • Now we can use the ES6 imports/exports syntax in index.js and anotherFile.js.
  • The index.js file exports a variable and a function.

index.js:

// Create a default export function say multiply which accepts
// two numbers as arguments and returns their multiplication result
export default function multiply(x, y) {
  // Returns the multiplication result of the passed two numbers
  return x * y;
}

// This is named export
export const id = 50;

Now we import the above index.js file into another file and can be accessed there.

index.js:

// Here we are importing the default and named export from the
// index.js file using the import keyword
import multiply, {id} from './index.js';

// Passing two numbers as arguments to the multiply() function
// (of index.js file) to get the multiplication of two numbers and
// print the result
console.log(multiply(3, 4)); // Output => 12
// Printing the 'id' variable value (of index.js file)
console.log(id); // Output => 50

Output:

12
50

NOTE:

Please keep in mind that each file can only have one default export.
In the browser, use this syntax (ES6 Modules) rather than the 'require()' function.

Alternatively, you can insert the index.js file’s script above the anotherFile.js file’s script, and the function and variables from the index.js file will be made available to anotherFile.js without exporting and importing them.

Here’s an example that doesn’t include any imports or exports.

index.js:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>

    <!--Here the index.js file is loaded first, hence we can use the functions of it in anotherFile.js file-->
    <script src="index.js"></script>
    <script src="another-file.js"></script>
  </body>
</html>

The index.js file just defines a function and a variable.

index.js:

// Create a default export function say multiply which accepts
// two numbers as arguments and returns their multiplication result
export default function multiply(x, y) {
  // Returns the multiplication result of the passed two numbers
  return x * y;
}

// This is named export
export const id = 50;

We can now utilize the function and variable in our other code without even having to import them.

anotherFile.js:

// Passing two numbers as arguments to the multiply() function
// (of index.js file) to get the multiplication of two numbers and
// print the result
console.log(multiply(3, 4)); // Output => 12
// Printing the 'id' variable value (of index.js file)
console.log(id); // Output => 50

Output:

12
50

Fixing the ERROR

If the require() function of the server is not specified/defined, we have set the type attribute/property to module in our package.jsonfile, or all files that have an extension of .mjs instead of .js.

To resolve the “ReferenceError require is not defined” error, remove the type property from your package.json file if it is set to the module and rename any files with file.mjs extension to have file.js extension.

package.json:

{
  // It should be removed if we want to use require
   "type": "module",
   
  // Write the rest of the code.....
}

You may also utilize the ES6 module syntax with the import and export keywords.

Set the type property in your package.json file to module if you wish to utilize the import/export syntax to import and export modules.

package.json:

{
  // Here we must add this below one
  "type": "module",
   // Write the rest of the code.....
}

We must have to replace the require and module.exports syntax with the import and export keywords.

Let us see an example where we define a function and a variable, and then export the function as a default export and the variable as a named export.

index.js:

// Create a function(default export) say multiply which accepts
// two numbers as arguments and returns their multiplication result
export default function multiply(x, y) {
  // Returns the multiplication result of the passed two numbers
  return x * y;
}

// This is named export
export const id = 50;

Now we are importing them into anotherFile.js from the above index.js file

anotherFile.js:

// Here we are importing the default and named import from the
// index.js file using the import keyword
import multiply, {id} from './index.js';

// Passing two numbers as arguments to the multiply() function
// (of index.js file) to get the multiplication of two numbers and
// print the result
console.log(multiply(2, 10)); // Output => 20
// Printing the 'id' variable value (of index.js file)
console.log(id); // Output => 50

Output:

20
50

NOTE:

  • As said earlier, please keep in mind that you can only use 1 default export per file.
  • You cannot use the require() function in combination with the ES6 Module import/export syntax. You must use one or the other on a consistent basis.

 

How to Fix Object is possibly ‘undefined’ error in TypeScript

How to Fix Object is possibly 'undefined' error in TypeScript

When we try to access a property on an object that may be undefined, we get the “Object is possibly ‘undefined'” error (example- marked as optional).

To fix the mistake, use optional chaining to short-circuit if the reference is null, such as e?.name?.salary.

index.ts

// Create a class
type Employ = {
  //  Create a nested objects which may be undefined 
  name?: { 
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ class
const e: Employ = {};

// When we try to get salary then we get => Error: Object is possibly 'undefined'.ts(2532)
e.name.salary;

Output:

Error: Object is possibly 'undefined'.ts(2532)

The nameproperty on the Employ type is marked as optional, so it may be undefined.

This is why we cannot safely access `address` or salaryproperties.

Fixing Object is possibly ‘undefined’ error in TypeScript

We can fix this error by using theoptional chaining (.) operator.

Method #1: Using Optional Chaining

// Create a class
type Employ = {
// Create a nested objects which may be undefined 
  name?: {
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ clas
const e: Employ = {};

// Here now we don't get any error.It works fine
const rslt = e?.name?.salary;

Explanation:

There will be NO errors in this case.

In TypeScript, the dot (?.) syntax is known as optional chaining. It is similar to using dot notation to access a nested property of an object, but instead of throwing an error if the reference is nullish (null or undefined), it short-circuits and returns undefined.

This method is typically used for retrieving data from a remote API or reading it from a file, where some of the 
properties may be empty.

Method #2: Using If Conditional Statement

We used an if statement to determine whether the e.name property is not equal to undefined or null.

// Create a class
type Employ = {
//  Create a nested objects which may be undefined 
  name?: {
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ class
const e: Employ = {};

// check if the name property of the employ class is not undefined using the optional chaining(.) and if conditional statement
if (e.name != undefined) {
  console.log(e.name.address?.toUpperCase);
  console.log(e.name.salary?.toUpperCase);
}

Explanation:

There will be NO errors in this case.

TypeScript knows that the e.nameis of type object and not undefined once we enter the if block.

Here we utilized loose not equals (!=) to check for both undefined and null values. You can only use strict not equals (!==) to check for undefined.

Because undefined is identical to null in a loose comparison, it covers both undefined and null.

console.log(undefined == null);  // output => true
console.log(undefined === null); // output => false

Output:

true
false

If you are certain that the property cannot have a null value, you can use the non-null assertion operator.

//  Create a class
type Employ = {
  name?: {
    address?: string;
    salary?: string;
  };
};

const e: Employ = {
  name: {
    address: 'Hyderabad',
    salary: '50000',
  },
};

console.log(e.name!.address); 
console.log(e.name!.salary);

Output:

Hyderabad
50000
  • In TypeScript, the exclamation mark(!) is the non-null assertion operator.
  • It removes null and undefined values from a type without performing any explicit type checking.
  • When you use this method, TypeScript is basically told that this value will never be null or undefined.
  • We used it right after the name property, so TypeScript knows that e.name will never be null or undefined

Method #3: Using Logical AND(&&) Operator

When comparing properties in an if statement, utilize the logical AND (&&) operator to ensure that the property is of the correct type.

// @@@

type Employ = {
  name?: {
    address?: string;
    salary?: number;
  };
};

const e: Employ = {};

if (
  e?.name &&
  typeof e.name.salary === 'string' &&
  e.name.salary > 1000
) {
  console.log('success');
}

Output:

Your program did not output anything!

Explanation:

Here the logical AND (&&) operator ensures that the property name is not undefined, that salary exists on the object and is a number before comparing it to the number 1000.

This is required because if the reference is nullish (null or undefined), the optional chaining operator (?.) would return undefined, and TypeScript does not support comparing undefined to a string.

How to Fix Property does not exist on type Object in TypeScript?

How to Fix Property does not exist on type Object in TypeScript

When we try to access a property that is not contained in the object’s type, we get the “Property does not exist on type Object” error.

To fix the error, explicitly type the object properties or use a type with variable key names.

Let us see an example to know how this error occurs

index.ts:

// Create an object and store it in a variable
const gvn_obj: Object = {
  EmpId: 6136,
  EmpName: 'John',
};

// Here the key salary does not exist on the above created object 'gvn_obj'
// So, when we try to access it we get a Property 'salary' does 
// not exist on type 'Object' Error.
gvn_obj.salary = 50000;

Output:

script.ts(10,9): error TS2339: Property 'salary' does not exist on type 'Object'.

Explanation:

Here we typed the gvn_obj variable as Object and tried to access the salary property on the object.

The salaryproperty, however, does not exist on the Object type, therefore the type checker returns an error.

Fixing Property does not exist on type Object Error in TypeScript

1)When you know property names ahead of time

// This is the case when you know property names ahead of time
// Give the type(datatypes) of property names (variable)
type FirstEmploy = {
  EmpName: string;
  EmpId: number;
  salary?: number;
};

// Create an object for the above type object 
const object_1: FirstEmploy = {
  EmpName: 'Alex',
  EmpId: 8459,
};

// Add a new key value value(here salary) to the above object using optional chaining(.) 
object_1.salary = 50000;

// Print the above object
console.log(object_1);

Output:

{ EmpName: 'Alex', EmpId: 8459, salary: 50000 }

Explanation:

  • Here it shows how to type an object when you know the property names and the types of the values ahead of time.
  • You can use a question mark(?) to indicate properties that you will not provide when initializing the object.
  • Now that the salary property exists in the object’s type, we can securely access it.

2)When you DON’T know All the property names ahead of time

You may not know the names of all of the object’s keys or the shape of the values ahead of time in some scenarios.

index.ts:

// This is the case when you don't know all the 
// property names ahead of time
type SecondEmploy  = {
  // we will use any if we dont know the type of variable
  [key: string]: any; 
  EmpName: string;
};

const object_2: SecondEmploy = {
  EmpName: 'Michel',
};
// Add the address field to the above created object using the optional chaining(.) operator
object_2.Address = 'Hyderabad';
object_2.EmpId = 2468;

// Print the above object
console.log(object_2);

Output:

{ EmpName: 'Michel', Address: 'Hyderabad', EmpId: 2468 }

Explanation:

The {[key: string]: any} syntax is known as an index signature, and it is used when the names of the object’s keys or the shape of the values are unknown ahead of time.

The syntax simply says that when the object is indexed with a string key, it will return a value of any type.

NOTE:

If you know any of the names of the properties ahead of time, you can specify them to improve type safety.

In the SecondEmploy type, we set the EmpName property to string so that the type checker would throw an error if the property was not provided or was set to a value of a different type.

You can use a more particular index signature for improved type safety if you don’t know the names of all of the object’s keys but know the shape of the values.

index.ts:

type SecondEmploy   = {
  [key: string]: string | number;
  EmpName: string;
  EmpId: number;
};

const object_2: SecondEmploy   = {
  EmpName: 'Michel',
  EmpId: 4586,
};

object_2.salary = 50000;
object_2.EmpAddress = 'Hyderabad';

console.log(object_2)

Output:

{
EmpName: 'Michel',
EmpId: 4586,
salary: 50000,
EmpAddress: 'Hyderabad'
}

The index signature in the preceding example indicates that when the object is indexed with a string key, it will return a value of type string or number.

In TypeScript, the string | number syntax is referred to as a union type.

Because the EmpName and EmpId properties are both strings and return distinct types, we had to utilize a union type.

In other words, you cannot specify that when the object is indexed with a string key, it returns a string value (type string) and then add another string key to the interface with a numeric value (type number).

index.ts:

type SecondEmploy = {
  [key: string]: string;
  EmpName: string;
  
  // Here we get an error i.e., Property 'EmpId' of type 'number' is not
  // assignable to string index type 'string'
  EmpId: number;
};

Output:

script.ts(7,3): error TS2411: Property 'EmpId' of type 'number' is not assignable to string index type 'string'.

 

How to Fix Unexpected end of JSON input Error in JavaScript?

How to Fix Unexpected end of JSON input Error in JavaScript

When attempting to parse invalid JSON using the JSON.parse or $.parseJSON functions, the “Unexpected end of JSON input” error occurs.

The issue arises while attempting to parse a value such as an empty array or string. To fix the issue, make sure the JSON is valid before parsing it.

Passing an Empty Array or String to the JSON.parse

index.html:

// Pass an empty array to the JSON.parse() function
// and print the result
console.log(JSON.parse([]));

// Pass an empty string to the JSON.parse() function
// and print the result
console.log(JSON.parse(''));

// Here in both the cases SyntaxError: Unexpected end of JSON
// input occurs

Output:

undefined:1


SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.<anonymous> (/tmp/ER7rLDlJor.js:3:18)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we got the error after passing an empty array and an empty string  
to the JSON.parse function. 
The same thing would happen if you used the $.parseJSON function.

Passing an Empty Array or String to the $.parseJSON() Function

// Pass an empty string to the $.parseJSON() function
// and print the result
// Here we get an error
console.log($.parseJSON(''));

Explanation:

The error occurs because we are attempting to parse invalid JSON.

The error also arises if you attempt to parse an empty server response or if your server fails to send the relevant CORS headers with the response.

If your server returns an empty response and you attempt to parse it, you will receive an error. You should delete the parsing logic in this situation.

If you’re getting the value from your server, ensure sure the server is setting Content-Type header to application/json.

Fixing Unexpected end of JSON input Error in JavaScript

The “Unexpected end of JSON input” error can be resolved in three ways:

  • In a try/catch block, wrap your parsing logic.
  • Ensure that your server returns a valid JSON response
  • If you expect an empty server response, remove the parsing logic from your code.

NOTE:

You may inspect your server's response by opening your developer tools
 and selecting the Network tab. 
The server's response can be viewed by clicking the Response tab.

Using try/catch Blocks to Avoid Error

index.html:

// Use try-catch blocks to avoid "Unexpected end of JSON input"
// error
try {
  // Pass an empty string to the JSON.parse() function
 // and store it in a variable
  const rslt = JSON.parse('');
  // Print the above result 
  console.log(rslt);
} 
// Handle the "Unexpected end of JSON input" Error inside the 
// catch block
catch (error) {
  // If the error occurs the print some random text and
  // corresponding error
  console.log('Sorry There is an Error!!!!\n', error);
}

Output:

Sorry There is an Error!!!!
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.<anonymous> (/tmp/ER7rLDlJor.js:6:21)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

If the JSON.parse() function returns an error as a result of parsing invalid JSON, the error is given as a parameter to the catch function, where it can be handled.

If you know the server’s response does not include valid JSON, you can delete/remove the call to the JSON.parse function.

You can also use an online JSON validator to determine whether a JSON string is valid.

 

How to get Jobs and Internships Using LinkedIn

How to get Jobs and Internships Using LinkedIn

In the article, we are going to see the step-by-step procedure for finding jobs and internships on LinkedIn.

Prerequisites:

  • Create your LinkedIn Account.
  • Try to fill all the fields on LinkedIn such as :
  1. Headline.
  2. Experiences.
  3. Skills.
  4. Projects.
  • Upload your resume to Google Drive and make it public. Include this link in your featured section so that recruiters can view your resume when they visit your profile.
  • Apply open to work for your profile picture.
  • Make a list of all the companies where you’d like to work.

Steps to Connect with Recruiters:

Step #1: Search for Hiring or Recruiter in LinkedIn Search Box

Type Recruiter or Hiring in the search box and click on People.

searching for recruiters

Step #2:

applying filters

Step #3:

step 3

Step #4:

Enter only one company name in Current Company Search Box.

step 4

Step #5:

After Selecting One Company click on show results.

step 5

Step #6:

Click on Connect/Message.

step 6

Step #7:

Click on Add a note.

step 7

Step #8:

Add a message with a summary of your skills, achievements, qualifications, and experiences, and ask if there are any job/internship opportunities that match our profile.

step 8

 

Repeat the above 8 steps by searching hiring in step 1 and changing the companies from the companies list.

Note:

Because the number of connections you can make every week/month on Linkedin is limited, connecting to 2-3 people for a single company is sufficient.

 

Python NumPy loadtxt() Function

Python NumPy loadtxt() Function

NumPy loadtxt() Function:

To load data from a text file, use the loadtxt() function of the NumPy module. In a text file, each row of the text file must have the same number of values.

Syntax:

numpy.loadtxt(filename, dtype=<class 'float'>)

Parameters

filename: This is required. The file, filename, or generator to read is specified by this argument. If the filename extension is.gz or.bz2, we’ll start by decompressing the file. After that, the generators will return Python 3k byte strings. It’s important to note that generators should only return byte strings.

dtype: This is optional. The datatype of the output array is indicated by this argument. float is the default value.

Return value

The data read from the text file is returned.

NumPy loadtxt() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword
  • Pass some random list as an argument to the array() function
    of the Numpy module to create an array.
  • Store it in a variable.
  • Save the above-given array as a text file with some random filename using the savetxt() function of the Numpy module
  • Load the above textfile using the loadtxt() function of the Numpy module
  • Print the above file content.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function
# of the Numpy module to create an array. 
# Store it in a variable.
gvn_arry = np.array([1, 12, 35, 20, 70])                     

# Save the above given array  as a text file with some random filename
# using the savetxt() function of the Numpy module
np.savetxt("samplefile", gvn_arry)

# Load the above textfile using the loadtxt() function of the Numpy module
file_content = np.loadtxt("samplefile")
print()
# Print the above file content
print("The above file content:")
print(file_content)

Output:

The above file content:
[ 1. 12. 35. 20. 70.]

Solved- TypeError: dict_keys object does not support indexing

Getting and resolving ‘TypeError: dict_keys object does not support indexing in Python’.

In this article we will discuss about

  • Reason of getting ‘TypeError: ‘dict_keys’ object does not support indexing’
  • Resolving the type error.

So let’s start exploring the topic.

To fetch keys, values or key-value pair from a dictionary in python we use functions like keys(), values() and items() which return view object so that we get a dynamic view on the dictionary entries.

The important point is that when dictionary changes then these views reflects these changes and we can iterate over it also. But when we want to use indexing on these objects then it causes TypeError.

Getting TypeError :

#Program :

# Dictionary created of string and int
word_freq = {
    'Aa' : 56,
    "Bb"    : 23,
    'Cc'  : 43,
    'Dd'  : 78,
    'Ee'   : 11
}

# Here, fetching a view object 
# by pointing to all keys of dictionary
keys = word_freq.keys()
print('dict_keys view object:')
print(keys)
print('Try to perform indexing:')

# Here, trying to perform indexing on the key's view object 
# Which will cause error
first_key = keys[0]
print('First Key: ', first_key)
Output :

Try to perform indexing:
Traceback (most recent call last):
File “temp.py”, line 18, in <module>
first_key = keys[0]
TypeError: ‘dict_keys’ object does not support indexing

Here, in the above example we got Type error as because we tryied to select value at index 0 from the dict_keys object, which is a view object and we know view object does not support indexing.

Resolving TypeError :

The solution to TypeError: dict_keys object does not support indexing is very simple. We just need to convert these view object dict_keys into a list and then we can perform indexing on that. Means we will cast the dict_keys object to list object and then selecting elements at any index position.

#Program :

# Dictionary created
word_freq = {
    'Aa' : 10,
    "Bb" : 20,
    'Cc' : 30,
    'Dd' : 40,
    'ee' : 50
}
# Here, fetching a view object 
# by pointing to all keys of dictionary
keys = list(word_freq.keys())
print('List of Keys:')
print(keys)

# Selecting 1st element from keys list
first_key = keys[0]
print('First Key: ', first_key)
Output :
List of Keys:
['Aa', 'Bb', 'Cc', 'Dd', 'Ee']
Second Key: Aa
In this example we converted all the keys of the dictionary to list and then we selected 1st element from the list which is present at index position 0 and it also returned the first key which is present at index position 0.