Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Add a key value pair to Dictionary in Python
Next article icon

Python Program to find XOR of all the key value pairs in a Dictionary

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a dictionary in python, write a program to find the XOR of all the key-value pairs in the dictionary and return in the form of an array.

Note: All the keys and values in the dictionary are integers.

Examples:

Input : dic={1:3, 4:5, 6:7, 3 :8}
Output : [2, 1, 1, 11]
Explanation: XOR of all the key-value pairs in the dictionary are [1^3, 4^5, 6^7, 3^8]
Thus, [2, 1, 1, 11]

Note: Order may change as the dictionary is unordered.

Method 1:

  • Start traversing the dictionary.
  • Maintain an array for storing the XOR of each key-value pair.
  • For each key in the dictionary, find  key^value and append the value to the array.
  • Finally, return the array.

Below is the implementation of the above approach

Python
def xorOfDictionary(dic):     # Array to store XOR values     arr = []      # Traversing the dictionary     for i in dic:         # Finding XOR of Key value.         cur = i ^ dic[i]         arr.append(cur)     return arr   dic = {5: 8, 10: 9, 11: 12, 1: 14} print(xorOfDictionary(dic)) 

Output
[13, 3, 7, 15]

Time complexity: O(n)
Auxiliary space : O(n) for storing XOR values.

Method  2:Using items() function

Python
def xorOfDictionary(dic):     # Array to store XOR values     arr = []      # Traversing the dictionary     for key, value in dic.items():         # Finding XOR of Key value.         cur = key ^ value         arr.append(cur)     return arr   dic = {5: 8, 10: 9, 11: 12, 1: 14} print(xorOfDictionary(dic)) 

Output
[13, 3, 7, 15]

Time complexity: where n is the number of items in the dictionary, because it has to traverse the dictionary once to calculate the XOR of each key-value pair.
Auxiliary space: O(n), because it needs to store all the XOR values in an array.

Method #3 : Using keys() and values() methods

Python
dic = {5: 8, 10: 9, 11: 12, 1: 14} arr = [] x=list(dic.keys()) y=list(dic.values()) for i in range(0,len(x)):     arr.append(x[i]^y[i]) print(arr) 

Output
[13, 3, 7, 15]

Time complexity: O(n)
Auxiliary space: O(n) for storing XOR values.

Method 4: Using a list comprehension

Python
def xorOfDictionary(dic):   # List comprehension to compute XOR values   return [i ^ dic[i] for i in dic]  dic = {5: 8, 10: 9, 11: 12, 1: 14} print(xorOfDictionary(dic)) 

Output
[13, 3, 7, 15]

Time complexity: O(n)
Auxiliary space: O(n) 

Method 5:Using the map() function and a lambda function

  • Traverse the dictionary using the .items() method.
  • For each key-value pair, apply the lambda function, which takes the XOR of the key and value.
  • The result of each XOR operation is stored in a list using the map() function.
  • Return the list of XOR values.

Code uses the map() function with a lambda function to perform the XOR operation on each key-value pair in the dictionary and store the result in a list.

Python
dict = {5: 8, 10: 9, 11: 12, 1: 14}  xor_res = list(map(lambda kv: kv[0] ^ kv[1], dict.items()))  # Result print(xor_res) 

Output
[13, 3, 7, 15]

The items() method is used by the map() function to extract the key-value pairs for each item in the dictionary. The list() method is used to turn iterable that the map() function returns into a list. The list of XOR results is printed last.

Time complexity: O(N) as the map() function and the lambda function are both applied to each key-value pair once, which takes O(1) time and there are a total of N key-value pairs. So time complexity is O(N).
Auxiliary space: O(n) as the list is of the same size as the number of key-value pairs in the dictionary. Therefore, the space complexity is O(N).



Next Article
Add a key value pair to Dictionary in Python
author
vinayedula
Improve
Article Tags :
  • Data Structures
  • DSA
  • Python
  • Python Programs
Practice Tags :
  • Data Structures
  • python

Similar Reads

  • Python Program to find XOR of values of all even keys in a dictionary
    Given a dictionary in Python, our task is to find the XOR of values of all even keys in a dictionary in Python. Note: All the keys and values in the dictionary are integers. Examples: Input : dic= {1:3, 4:5, 6:7, 3 :8}Output : 2Explanation: Even keys in the dictionary are 4,6 and their values are 5,
    5 min read
  • Python Program to print sum of all key value pairs in a Dictionary
    Given a dictionary arr consisting of N items, where key and value are both of integer type, the task is to find the sum of all key value pairs in the dictionary. Examples: Input: arr = {1: 10, 2: 20, 3: 30}Output: 11 22 33Explanation: Sum of key and value of the first item in the dictionary = 1 + 10
    5 min read
  • Python program to find the key of maximum value tuples in a dictionary
    Given a dictionary with values as tuples, the task is to write a python program to find the key of maximum value tuples. Examples: Input : test_dict = {'gfg' : ("a", 3), 'is' : ("c", 9), 'best' : ("k", 10), 'for' : ("p", 11), 'geeks' : ('m', 2)}Output : forExplanation : 11 is maximum value of tuple
    6 min read
  • Add a key value pair to Dictionary in Python
    The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
    3 min read
  • Python program to multiply all the items in a dictionary
    Python program to illustrate multiplying all the items in a dictionary could be done by creating a dictionary that will store all the key-value pairs, multiplying the value of all the keys, and storing it in a variable. Example: Input: dict = {'value1':5, 'value2':4, 'value3':3, 'value4':2, 'value5'
    2 min read
  • Python Program to display keys with same values in a dictionary List
    Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries. Examples: Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}] Output : ['Gfg', 'best'
    5 min read
  • Python program to group keys with similar values in a dictionary
    Given a dictionary with values as a list. Group all the keys together with similar values. Input : test_dict = {"Gfg": [5, 6], "is": [8, 6, 9], "best": [10, 9], "for": [5, 2], "geeks": [19]} Output : [['Gfg', 'is', 'for'], ['is', 'Gfg', 'best'], ['best', 'is'], ['for', 'Gfg']] Explanation : Gfg has
    2 min read
  • Python program to Count the Number of occurrences of a key-value pair in a text file
    Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file with Python Program to Count the occurrences of a key-value pairNaive Approach to Count the Occurrences of a key-value PairUsing Python built-in collections.CounterUsing regular ex
    3 min read
  • Get First N Key:Value Pairs in given Dictionary - Python
    We are given a dictionary and tasked with retrieving the first N key-value pairs. For example, if we have a dictionary like this: {'a': 1, 'b': 2, 'c': 3, 'd': 4} and we need the first 2 key-value pairs then the output will be: {'a': 1, 'b': 2}. Using itertools.islice()One of the most efficient ways
    3 min read
  • Extract Subset of Key-Value Pairs from Python Dictionary
    In this article, we will study different approaches by which we can Extract the Subset Of Key-Value Pairs From the Python Dictionary. When we work with Python dictionaries, it often involves extracting subsets of key-value pairs based on specific criteria. This can be useful for tasks such as filter
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences