Как разделить словарь на части python
Перейти к содержимому

Как разделить словарь на части python

  • автор:

Как разделить словарь на части python

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

Method 1: Split dictionary keys and values using inbuilt functions

Here, we will use the inbuilt function of Python that is .keys() function in Python, and .values() function in Python to get the keys and values into separate lists.

Python3

Output:

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

Method 2: Split dictionary keys and values using zip()

Here, we will use the zip() function of Python to unpack the keys and values from the dictionary.

Python3

Output:

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

Method 3: Split dictionary keys and values using items()

Here, we will use a Python loop and append the keys and values to the list using .items() function that will extract the keys and values from the dictionary.

Python3

Output:

Method 4 : Iterating a for loop over dictionary

Python3

Method 5: Using List Comprehension

  • Create two separate lists using list comprehension to store keys and values of the dictionary.
  • Iterate over the dictionary using the items() method to extract the keys and values.
  • Store the keys and values in separate lists using list comprehension.
  • Print the keys and values lists.

Below is the implementation of the above approach:

Python3

Time complexity: O(n) where n is the number of key-value pairs in the dictionary. List comprehension takes linear time complexity to create a list.
Auxiliary space: O(n) as we are creating two lists to store the keys and values of the dictionary.

How to Slice a Dictionary in Python

With Python, we can easily slice a dictionary to get just the key/value pairs we want. To slice a dictionary, you can use dictionary comprehension.

In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily access certain elements.

To slice a dictionary given a list of keys, we can use dictionary comprehension to loop over each item and return the items which have keys in our list.

Below is a simple example in Python of how to slice a dictionary given a list of keys.

Slicing the First N Items of a Dictionary with islice() Function in Python

If you want to slice the first n key/value pairs from a dictionary, we can use a different method from above.

The itertools module has many great functions which allow us to iterate over collections and perform complex tasks easily.

One function which is useful is the itertools islice() function. We can slice items out of a dictionary with islice()

For example, to slice the first two items out of a dictionary, we pass dict.items() and 2 to islice()

Below is an example of how to get the first n items of a dictionary in Python.

Hopefully this article has been useful for you to learn how to slice dictionaries in your Python programs.

Other Articles You'll Also Like:

  • 1. Python acos – Find Arccosine and Inverse Cosine of Number
  • 2. Python Replace Space with Underscore Using String replace() Function
  • 3. How to Split a String in Half Using Python
  • 4. Using Python to Count Number of Lines in String
  • 5. Using Python to Split String into Dictionary
  • 6. Drop Duplicates pandas – Remove Duplicate Rows in DataFrame
  • 7. numpy pi – Get Value of pi Using numpy Module in Python
  • 8. Write Inline If and Inline If Else Statements in Python
  • 9. Adjusting Python Turtle Screen Size with screensize() Function
  • 10. How to Check if List is Empty in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

Разбить dict на строки python?

phaggi

Рекомендую показать свою попытку решения вопроса, иначе см.п.5.12
Рекомендую показать свой код, решающий вопрос, что получилось, что ожидалось, если были — полные сообщения об ошибке.

kshnkvn

Gremlin92

kshnkvn

Gremlin92

phaggi

kshnkvn

MinTnt

phaggi

Ivan Yakushenko, это вам «изнутри» кажется всё просто. Когда приходишь из VBA или Cpp в Python, кое-что совершенно не интуитивно. Само слово «литерал» по отношению к тем же скобкам не воспринимается как что-то, на что надо обратить внимание.

Ну и потом, литералы порой ведут себя не совсем так, как вроде бы заменяемые ими операторы или функции. Это становится более-менее понятно, когда вникаешь в объектную модель языка.

А на начальном уровне Python выглядит как бейсик из Spectrum, только со странным поведением скобок.

phaggi

Для начала преобразуй это в словарь:

Непонятно, какой . (глупый человек) запаковал данные в таком виде, что распарсить их можно только через небезопасный eval()? Неужели нельзя было использовать JSON?

Split a dictionary in half?

It does not matter which keys/values go into each dictionary. I am simply looking for the simplest way to divide a dictionary into two.

martineau's user avatar

9 Answers 9

This would work, although I didn’t test edge-cases:

Also note that order of items is not guaranteed

Here’s a way to do it using an iterator over the items in the dictionary and itertools.islice :

If you use python +3.3 , and want your splitted dictionaries to be the same across different python invocations, do not use .items , since the hash-values of the keys, which determines the order of .items() will change between python invocations. See Hash randomization

The Hungry Dictator's user avatar

The answer by jone did not work for me. I had to cast to a list before I could index the result of the .items() call. (I am running Python 3.6 in the example)

Note the dicts are not necessarily stored in the order of creation so the indexes may be mixed up.

Here is the function which can be used to split a dictionary to any divisions.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *