
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a Python dictionary from text file?
Assuming a following text file (dict.txt) is present
1 aaa
2 bbb
3 ccc
Following Python code reads the file using open() function. Each line as string is split at space character. First component is used as key and second as value
d = {} with open("dict.txt") as f: for line in f: (key, val) = line.split() d[int(key)] = val print (d)
The output shows contents of file in dictionary form
{1: 'aaa', 2: 'bbb', 3: 'ccc'}
- Related Questions & Answers
- How to create a Pandas series from a python dictionary?
- How to create Python dictionary from JSON input?
- How to create Python dictionary from the value of another dictionary?
- Python program to create a dictionary from a string
- In Python how to create dictionary from two lists?
- How to create a dictionary in Python?
- How to save a Python Dictionary to CSV file?
- How to create a Python dictionary from an object's fields?
- How to read an entire line from a text file using Python?
- How to read a number of characters from a text file using Python?
- How to create nested Python dictionary?
- How to read a text file in Python?
- Python – Create dictionary from the list
- How we can create a dictionary from a given tuple in Python?
- How to create Python dictionary from list of keys and values?
Advertisements