A one liner, just for fun:

all_examples = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))

Produces:

[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, 
 {'A': 1, 'C': 4, 'B': 1, 'D': 5}]

As a bonus, this will work for longer sequences too:

all_examples = ['A,1,1,1', 'B,2,1,2', 'C,4,4,3', 'D,4,5,6']

Output:

[{'A': 1, 'C': 4, 'B': 2, 'D': 4},
 {'A': 1, 'C': 4, 'B': 1, 'D': 5},
 {'A': 1, 'C': 3, 'B': 2, 'D': 6}]

Explanation:

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))
  • [... for s in all_examples] For each element in your list:
  • s.split(',')[1:] Split it by commas, then take each element after the first
  • (...) for x in and turn it into a list of tuples
  • s[0], int(x) of the first letter, with that element converted to integer
  • zip(*[...]) now transpose your lists of tuples
  • map(dict, ...) and turn each one into a dictionary!
Answer from tzaman on Stack Overflow
Top answer
1 of 4
7

A one liner, just for fun:

all_examples = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))

Produces:

[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, 
 {'A': 1, 'C': 4, 'B': 1, 'D': 5}]

As a bonus, this will work for longer sequences too:

all_examples = ['A,1,1,1', 'B,2,1,2', 'C,4,4,3', 'D,4,5,6']

Output:

[{'A': 1, 'C': 4, 'B': 2, 'D': 4},
 {'A': 1, 'C': 4, 'B': 1, 'D': 5},
 {'A': 1, 'C': 3, 'B': 2, 'D': 6}]

Explanation:

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))
  • [... for s in all_examples] For each element in your list:
  • s.split(',')[1:] Split it by commas, then take each element after the first
  • (...) for x in and turn it into a list of tuples
  • s[0], int(x) of the first letter, with that element converted to integer
  • zip(*[...]) now transpose your lists of tuples
  • map(dict, ...) and turn each one into a dictionary!
2 of 4
4

Also just for fun, but with a focus on understandability:

all_examples = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
ll = [ x.split(",") for x in all_examples ]
ld = list()
for col in range(1, len(ll[0])):
    ld.append({ l[0] : int(l[col]) for l in ll })
print ld

will print

[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]

Works as long as the input is csv with integers and lines are same length.

Dissection: I will use the teminology "thing" for A, B and C and "measurement" for the "columns" in the data, i.e. those values in the same "csv-column" of the inut data.

Get the string input data into a list for each line: A,1,1 -> ["A","1","1"]

ll = [ x.split(",") for x in all_examples ]

The result is supposed to be a list of dicts, so let's initialize one:

ld = list()

For each measurement (assuming that all lines have the same number of columns):

for col in range(1, len(ll[0])):

Take the thing l[0], e.g. "A", from the line and assign the numeric value int(), e.g. 1, of the measurement in the respective column l[col], e.g. "1", to the thing. Then use a dictionary comprehension to combine it into the next line of the desired result. Finally append() the dict to the result list ld.

    ld.append({ l[0] : int(l[col]) for l in ll })

View unfoamtted. Use print json.dumps(ld, indent=4) for more convenient display:

print ld

Hope this helps. Find more on dict comprehensions e.g. here (Python3 version of this great book).

🌐
Scaler
scaler.com › home › topics › list of dictionaries in python
List of Dictionaries in Python - Scaler Topics
March 31, 2024 - Learn ways to create a Python list of dictionaries, and how to access them and modify them on Scaler Topics.
Discussions

How to properly copy a list of dictionaries in python?
I’ve been having trouble with a script and I isolated the issue to the fact that my for loops are somehow modifying an unrelated list (as far as I can tell). I replicated the result with this piece of code: list1 = [{"k… More on forum.inductiveautomation.com
🌐 forum.inductiveautomation.com
5
0
December 29, 2021
Seeking to populate a dictionary from a series of lists
I am seeking to populate a new dictionary from a series of lists. These separate lists contain information to specific categories like employee name, employee wage, employee ID number, etc. I have previously used “append” to add to lists, but I believe that this dictionary needs to be in ... More on discuss.python.org
🌐 discuss.python.org
19
0
September 7, 2022
how to know when to use Lists and when to Use dictionaries?

This is a complex question because there are times when either a dictionary, list, or tuple will work; and there are times where only one or two would work.

Dict

A dict does not* maintain order. Think of it like a literal dictionary: if I want to know the value of something, I just have to know its key. It's location inside the dict is completely irrelevant as long as I know the key. This makes it great for retrieving things that you can give a logical name to and updating things that you can give a logical name to. It's extremely fast for looking up the value of something. similar to a real dictionary, you have a good idea of where to start "searching" in an actual dictionary to find a word and don't have to flip through each and every page of the dictionary to find what you're looking for.

List

A list maintains order. If I load values into a list, they're always guaranteed to be in that order forever unless I explicitly change it. This isn't the case with dicts*. This allows you to do things like sort and order data in meaningful ways. A draw back with a list is that finding out if a value exists in a list could take a very long time if the items are unordered.

If I have an unordered list like this:

[['Hannah', 'black'], ['Mark', 'brown'], ['Avery', 'blonde'],....]

And I want to lookup the hair color of 'Peter', I have to search through every single value in the list to see if it matches Peter. If 'Peter' doesn't exist in the list, I will have gone through every value in the list. If the list of thousands of names long, this will take thousands of operations. However, if I had a dict mapping name to hair color, looking up if Peter exists in the dict would take roughly 1 operation, even if the dict was millions of mappings long.

Tuple

Tuples a bit like immutable lists. Meaning they hold values, and maintain order, but once you create one, you can never modify/add/or delete any of its values. A good use case of a tuple are related data that comes in fixed sizes and the order has a specific meaning:

# rgb color values
rgb = (255, 120, 30)

# x, y coordinates
coordinate = (-1, 0)

Tuples are also great for what I think of as "throw-away-lists". A list that you only use once, that will never grow, shrink, or change values can probably be turned into a tuple.

for name in ['Bob', 'Peter', 'Sarah']:
    print(name)


for name in ('Bob', 'Peter', 'Sarah'):
    print(name)

In the example above, both have the exact same output, although you will see people use either one. The list of names is never growing, shrinking, or changing value, so it can be converted to a tuple and probably should be converted to a tuple because a tuple is more efficient than a list.

-------------------------------------------------------------

In your example both dicts and lists would work, so why did the Automate The Boarding Stuff book use a dict for the Tic Tac Toe board instead of a list? (1) Probably because dict is a little harder to grasp so it would be good practice for the reader to get more exposure to using a dict. (2) If we did the list implementation, you would have to put the board in some type of order. Like this:

['', 'X', 'O', '', 'X', '', 'X', 'O', 'O']

One problem with the list implementation is that it is not obvious which index corresponds to which square on a Tic Tac Toe board. Are the first 3 indexes representing the top row? Or do they represent the left column? There's no way to really telling from the code alone. With the dict implementation, it's extremely obvious which value corresponds to which square on a Tic Tac Toe board.

But in this case, yes either a list or dict would work. A tuple would probably not be a great idea because it's immutable, and you can't update the values it holds without creating a brand new tuple.

-------------------------------------------------------------

* later version of Python does maintain dict entry order

More on reddit.com
🌐 r/learnpython
5
2
December 19, 2021
When to use array vs. list (vs dict)
If you're specifically dealing with matrices and need to perform maths on them, or have a specific use-case where the performance benefits would be needed, use Numpy arrays. Keep in mind that if you're constantly converting between lists and Numpy arrays that'll probably eat up any performance gains you got, so if you go this route do as much as you can with Numpy's own functionality. Otherwise, default to lists. There's technically also array.array in the standard library, but I say ignore it. You won't have a use for it unless you're specifically interfacing with C code. EDIT: And remember, your algorithm matters far more than the data structure. So don't treat Numpy as a silver bullet for performance gains. As for dictionaries, at some point you'll intuitively know when to use one, but if you want to map one set of values to another that's a pretty good candidate. More on reddit.com
🌐 r/learnpython
14
13
November 14, 2023
🌐
Reddit
reddit.com › r/learnpython › better way to manage list of dicts?
r/learnpython on Reddit: Better way to manage list of dicts?
November 26, 2021 -

I write web scrapers and often work with a huge list of dictionaries.

All of the dictionaries are identical or near identical in terms of their keys.

Each dictionary represents content scraped from a webpage.

Often time I find myself looping through the list of dictionaries to perform operations but I feel like there must be a better way. Is there anyway I can treat them all as one dictionary and apply functions to a particular key?

Any advice would be appreciated tia

🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.6 documentation
Similarly to list comprehensions, set comprehensions are also supported: >>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'r', 'd'} Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-create-list-of-dictionary-in-python
How to create list of dictionary in Python - GeeksforGeeks
July 23, 2025 - In this article, we are going to discuss ways in which we can create a list of dictionaries in Python.
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-through-list-of-dictionaries-in-python
Iterate through list of dictionaries in Python - GeeksforGeeks
July 23, 2025 - List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game Development'}, {'Java': 'App Development', 'Kotlin': 'App Development'}] This is a direct method, where list elements are extracted using just the index.
Find elsewhere
🌐
Enki
enki.com › post › list-and-dict-in-python
Enki | Blog - Difference Between list and dict in Python
Mutability and Order: While both data structures are mutable, their handling of order differs. Lists maintain the order of elements, whereas dictionaries, despite keeping insertion order from Python 3.7, focus on efficient key lookups.
🌐
Medium
medium.com › @cssjhnnamae › use-cases-of-python-lists-of-dictionaries-df6f32a4dba0
Use Cases of Python Lists of Dictionaries | by Princess Rodiel | Medium
September 17, 2024 - This example shows how to add a new dictionary to an existing list of dictionaries (ls). Here’s what happens: ... dict_to_append: This is a new dictionary { ‘language’: ‘Python’, ‘Framework’: ‘Django’ } that we want to add to ls.
🌐
PacketPushers
packetpushers.net › home › how to reference nested python lists & dictionaries
How To Reference Nested Python Lists & Dictionaries
January 26, 2024 - A Python list can contain a dictionary as a list item. Here’s a list containing a mix of string objects and dictionaries.
🌐
Inductive Automation
forum.inductiveautomation.com › ignition
How to properly copy a list of dictionaries in python? - Ignition - Inductive Automation Forum
December 29, 2021 - I’ve been having trouble with a script and I isolated the issue to the fact that my for loops are somehow modifying an unrelated list (as far as I can tell). I replicated the result with this piece of code: list1 = [{"key1": 1, "key2": 2}] list2 = list(list1) print "ID of list1: " + str(id(list1)) print "ID of list2: " + str(id(list2)) print "Contents of list1: " + str(list1) print "Contents of list2: " + str(list2) list2[0]["key1"] = 999 print "ID of list1: " + str(id(list1)) print "ID o...
🌐
Untitled Publication
rodny.hashnode.dev › understanding-lists-of-dictionaries-in-python
Understanding Lists of Dictionaries in Python
I’ve created another five List of Dictionaries to show how to do it properly. For the book list of dic... ... With a deep understanding of Python's dictionary data structure, we have to master and remember some of the fundamentals in creating a dictionary, allowing me to efficiently manipulate, organize, and analyze data through dynamic operations like addin...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-ways-to-create-a-dictionary-of-lists
Ways to create a dictionary of Lists - Python - GeeksforGeeks
July 11, 2025 - A dictionary where each key is paired with a list (e.g., [1, 2]). This is the most straightforward way to define a dictionary of lists but requires hardcoding all the keys and values.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-list-of-dictionaries-to-dictionary-value-list
Python - Convert list of dictionaries to Dictionary Value list - GeeksforGeeks
July 15, 2025 - Using dictionary comprehension, we can convert a list of dictionaries into a dictionary of value lists by iterating over the keys of the first dictionary to define the keys of the result. Python ·
🌐
Python
docs.python.org › 3 › library › collections.html
collections — Container datatypes
Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory. defaultdict objects support the following instance variable: ... This attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent. Changed in version 3.9: Added merge (|) and update (|=) operators, specified in PEP 584. Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:
🌐
Built In
builtin.com › software-engineering-perspectives › convert-list-to-dictionary-python
10 Ways to Convert Lists to Dictionaries in Python | Built In
By using collections.ChainMap(), we can convert a list of dictionaries to a single dictionary. “ChainMap: A ChainMap groups multiple dicts or other mappings together to create a single, updateable view,” according to Python’s documentation.
🌐
New York University
physics.nyu.edu › pine › pymanual › html › chap3 › chap3_arrays.html
3. Strings, Lists, Arrays, and Dictionaries — PyMan 0.9.31 documentation
The elements of lists and arrays are numbered consecutively, and to access an element of a list or an array, you simply refer to the number corresponding to its position in the sequence. The elements of dictionaries are accessed by “keys”, which can be either strings or (arbitrary) integers (in no particular order). Dictionaries are an important part of core Python.
🌐
W3Schools
w3schools.com › python › python_dictionaries.asp
Python Dictionaries
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates. As of ...
🌐
W3Schools
w3schools.com › python › python_lists.asp
Python Lists
In Python 3.6 and earlier, dictionaries are unordered. When choosing a collection type, it is useful to understand the properties of that type.
🌐
Medium
medium.com › @ericvanrees › python-workout-lists-and-dictionaries-506fe07fc8b7
Python Workout — Lists and Dictionaries
September 24, 2023 - If a key appears in more than one argument, the value should be a list containing all of the values from the arguments.""" def list_of_dicts(mylist): for item in mylist: newdict = {} for item in mylist: for k, v, in item.items(): if k in newdict: newdict[k].append[v] else: newdict[k] = [v] return newdict list_of_dicts([{'a': 1, 'b': 2, 'c': 3}, {'d': 3, 'e': 9, 'g': 8}]) # will output {'a': [1], 'b': [2], 'c': [3], 'd': [3], 'e': [9], 'g': [8]}
🌐
Python.org
discuss.python.org › python help
Seeking to populate a dictionary from a series of lists - Python Help - Discussions on Python.org
September 7, 2022 - I am seeking to populate a new dictionary from a series of lists. These separate lists contain information to specific categories like employee name, employee wage, employee ID number, etc. I have previously used “append” to add to lists, but I believe that this dictionary needs to be in ...