- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 Python dictionary with duplicate keys?
Python dictionary doesn't allow key to be repeated. However, we can use defaultdict to find a workaround. This class is defined in collections module.
Use list as default factory for defaultdict object
>>> from collections import defaultdict >>> d=defaultdict(list)
Here is a list of tuples each with two items. First item is found to be repeatedly used. This list is converted in defaultdict
>>> for k,v in l: d[k].append(v)
Convert this defaultdict in a dictionary object using dict() function
>>> dict(d) {1: [111, 'aaa'], 2: [222, 'bbb'], 3: [333, 'ccc']}
Advertisements