Open In App

Python – Append Dictionary Keys and Values ( In order ) in dictionary

Last Updated : 30 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary, perform append of keys followed by values in list.

Input : test_dict = {“Gfg” : 1, “is” : 2, “Best” : 3} 
Output : [‘Gfg’, ‘is’, ‘Best’, 1, 2, 3] 
Explanation : All the keys before all the values in list. 

Input : test_dict = {“Gfg” : 1, “Best” : 3} 
Output : [‘Gfg’, ‘Best’, 1, 3] 
Explanation : All the keys before all the values in list.

Method #1 : Using list() + keys() + values()

This is one of the ways in which this task can be performed. In this, we extract keys and values using keys() and values(), convert then to list using list() and perform append in order.

Python3




# Python3 code to demonstrate working of
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using values() + keys() + list()
 
# initializing dictionary
test_dict = {"Gfg" : 1, "is" 3, "Best" : 2}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# + operator is used to perform adding keys and values
res = list(test_dict.keys()) + list(test_dict.values())
 
# printing result
print("The ordered keys and values : " + str(res))


Output

The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using chain() + keys() + values()

This is one of the ways in which this task can be performed. In this, we bind keys with values together in order using chain().

Python3




# Python3 code to demonstrate working of
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using chain() + keys() + values()
from itertools import chain
 
# initializing dictionary
test_dict = {"Gfg" : 1, "is" 3, "Best" : 2}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# chain() is used for concatenation
res = list(chain(test_dict.keys(), test_dict.values()))
 
# printing result
print("The ordered keys and values : " + str(res))


Output

The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]

Time complexity: O(n), where n is the size of the dictionary.
Auxiliary space: O(n), as we are creating a list of size 2n to store the concatenated keys and values.

Method #3 : Using  list() +keys() + values() + extend()

Python3




# Python3 code to demonstrate working of
# Append Dictionary Keys and Values
#( In order ) in dictionary
# Using values() + keys() + extend()+list()
 
# initializing dictionary
test_dict = {"Gfg": 1, "is": 3, "Best": 2}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
a = list(test_dict.keys())
b = list(test_dict.values())
a.extend(b)
res = a
 
# printing result
print("The ordered keys and values : " + str(res))


Output

The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary. 

Method #4: Using zip() function and list comprehension

This program initializes a dictionary and prints it. It then uses a zip() function and list comprehension to create a list of key-value pairs where the values come first, and then the keys. It finally prints the ordered key-value pairs.

Python3




# initializing dictionary
test_dict = {"Gfg": 1, "is": 3, "Best": 2}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using the zip() function and list comprehension to append dictionary keys and values
res = [val for val in zip(test_dict.values(), test_dict.keys())]
 
# printing result
print("The ordered keys and values : " + str(res))


Output

The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : [(1, 'Gfg'), (3, 'is'), (2, 'Best')]

Time complexity: O(n), where n is the number of items in the dictionary. 
Auxiliary space: O(n), as we are creating a list of n items using the list comprehension.

Method #5: Using sorted() function and list comprehension

Step-by-step approach:

  • Initialize the dictionary test_dict.
  • Print the original dictionary using the print() function.
  • Use the sorted() function to get the keys in alphabetical order, and assign the result to the keys variable.
  • Use a list comprehension to get the values corresponding to each key in the keys list, and assign the result to the values variable.
  • Concatenate the keys and values lists using the + operator, and assign the result to the res variable.
  • Print the ordered keys and values using the print() function.

Python3




# Python3 code to demonstrate working of
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using sorted() + list comprehension
 
# initializing dictionary
test_dict = {"Gfg" : 1, "is" 3, "Best" : 2}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using sorted() to get the keys in alphabetical order
keys = sorted(test_dict.keys())
 
# using list comprehension to get the values corresponding to each key
values = [test_dict[key] for key in keys]
 
# concatenating the keys and values lists
res = keys + values
 
# printing result
print("The ordered keys and values : " + str(res))


Output

The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Best', 'Gfg', 'is', 2, 1, 3]

Time complexity: Sorting takes O(n log n) time, and list comprehension takes O(n) time. Therefore, the overall time complexity of this method is O(n log n).

Auxiliary space: This method creates two additional lists (keys and values) of size n, so the auxiliary space complexity is O(n).



Similar Reads

Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Python - Append Multitype Values in Dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to update the dictionary values, according to the data type. This type of problem can have application in many domains which include data. Lets discuss a way in which this problem can be solved. Input : test_dict = {'gfg' : "", 'is' : {}, 'best' : []} Output : {
4 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values): One naive solution maybe something like just swa
4 min read
Python | Test if dictionary contains unique keys and values
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it
6 min read
Python - Sort Dictionary by Values and Keys
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexicographically sorted keys. Input : test_dict = {"gfg
3 min read
Initialize Python Dictionary with Keys and Values
In this article, we will explore various methods for initializing Python dictionaries with keys and values. Initializing a dictionary is a fundamental operation in Python, and understanding different approaches can enhance your coding efficiency. We will discuss common techniques used to initialize Python dictionaries with keys and values, accompan
3 min read
Python Print Dictionary Keys and Values
Python, a versatile and powerful programming language, offers multiple ways to interact with and manipulate data structures. Among these, dictionaries are widely used for storing key-value pairs. When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll ex
2 min read
Iterate Through Dictionary Keys And Values In Python
In Python, a Dictionary is a data structure where the data will be in the form of key and value pairs. So, to work with dictionaries we need to know how we can iterate through the keys and values. In this article, we will explore different approaches to iterate through keys and values in a Dictionary in Python. Iterate Through Dictionary Keys And V
2 min read
Practice Tags :
three90RightbarBannerImg