List comprehension - attempting to create dictionary from array of key-value pair arrays

dictionary comprehension python
python dictionary
nested list comprehension python
list comprehension python for loop
python create dictionary from list
write a python program to map two lists into a dictionary
python list comprehension if
how to combine two lists into a dictionary python

While trying to create a dict using list comprehension (without overwriting generated list keys)

x = {}
entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
discardable = [x.setdefault(entry[0], []).append(entry[1]) for entry in entries]

Error: name 'x' is not defined

I was expecting x to be populated as:

{1: ['1a', '1b'], 2: ['2a', '2b'], 3: ['3a', '3b']}

How to explain this / make this work? Is there any other way to achieve this?

Some of the keys are str and some are int, so this will produce

{'1': ['1a', '1b'], 2: ['2a'], 3: ['3a'], '2': ['2b'], '3': ['3b']}

You need to cast entry[0] to int

x = {}
entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
[x.setdefault(int(entry[0]), []).append(entry[1]) for entry in entries]

print(x) will give

{1: ['1a', '1b'], 2: ['2a', '2b'], 3: ['3a', '3b']}

Create an array of dictionaries from a Python list, python arrays json dictionary list-comprehension Or have each pair as its own dictionary. Using your original attempt: You just need to make the object and specify the keys. d = map(dict, map(lambda t:zip(('value','score'),t), zip(my_list[:: 2], my_list[1::2]))) print(list(d)) Using List Comprehension: Edit: So almost 5 years later, this answer is getting downvotes because it’s not creating an “normal” JS object literal (aka map, aka hash, aka dictionary). It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with key and value properties.

You can try:

from collections import defaultdict
entries = [['1','1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
x = defaultdict(list)
[x[a].append(b) for a,b in entries]
x = dict(x)

Output

{'1': ['1a', '1b'], 2: ['2a'], 3: ['3a'], '2': ['2b'], '3': ['3b']}

How do you convert two lists into a dictionary?, I have two lists: keys = ['Name','Emp ID','Contact Info'] values = ['Ken','ED445','### ######'] , 'Emp ID' : ED445, There are three different ways of converting two lists into key:value pair dictionary. #using dictionary comprehension to convert list into dictionary You could try using the AST module. Append a new key value pair in dictionary # Adding a new key value pair wordFreqDic.update( {'before' : 23} ) It will add a new key value pair in the dictionary. Dictionary contents will be now test :: 43 this :: 43 Hello :: 56 at :: 23 before :: 23 If key is string you can directly add without curly braces i.e. # Adding a new key value pair

What you want is to merge the value of (1, '1'), (2, '2'), (3, '3'). The code you provided works, but it doesn't handle the type between int and str. All you need to do is cast str into int so the value would be merged.

Try this:

x = {}
entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
discardable = [x.setdefault(int(entry[0]), []).append(entry[1]) for entry in entries]

When to Use a List Comprehension in Python – Real Python, Python list comprehensions make it easy to create lists while performing To create the squares dictionary, you use curly braces ( {} ) as well as a key-value pair ( i: i * i ) in your expression. That's because Python is trying to create a list with one billion But it is best when apply to arrays of numbers. How to Create Key Value Pair Array Using Javascript. By Yashwant Chavan, Views 500427, Last updated on 01-Mar-2013. Our today's article is simple but demanding. Most of the new or experience java-script developer required below code. In this code snippet I have define java-script array values are in the form of key and value.

How to explain this / make this work?

A comprehension creates one output for each input, and they're not intended for mutation

Is there any other way to achieve this?

Use a normal procedural loop. Or use a multidict but the standard library doesn't provide one.

You could perform functional transformations until you get the proper "shape" (using sorted, itertools.groupby and some more mapping) but I don't think that'd be worth it, a bog-standard for loop would be much more readable:

for k, v in entries:
    x.setdefault(int(x), []).append(v)

versus:

x = {
    x: list(v[1] for v in vs)
    for x, vs in itertools.groupby(
        sorted((int(k), v) for k, v in entries),
        lambda it: it[0]
    )
}

the comprehension is less readable and less efficient

Python Dictionary Comprehension Tutorial, Learn all about Python dictionary comprehension: how you can use it to What you now deal with is a "key-value" pair, which is sometimes a more you try to find the meaning using the word itself and not the possible index of the word. While lists, dictionaries, and sets other than frozensets are not. PHP offers us a special type of array called an Associative Array that allows us to create an array with Key-Value pairs. The syntax for creating an Associative Array is as follows: Syntax 1: Using array() constructor

You can use a dict comprehension. they work much like list comprehensions

entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]

# Build a dictionary from the values in entries
discardable = {key:val for key, val in entries}

print (discardable)
# Result: {1: '1a', 2: '2a', 3: '3a', '1': '1b', '2': '2b', '3': '3b'}

(Tutorial) Python List Comprehension, Learn how to effectively use list comprehension in Python to create lists, Instead, you store all of these values in a Python list. The list is capable of holding various data types inside it, unlike arrays. Lambda functions borrow their name from the lambda keyword in Python, which is used to declare� 3. Strings, Lists, Arrays, and Dictionaries¶ The most import data structure for scientific computing in Python is the NumPy array. NumPy arrays are used to store lists of numerical data and to represent vectors, matrices, and even tensors. NumPy arrays are designed to handle large data sets efficiently and with a minimum of fuss.

Python Tutorial: Dictionaries, Tutorial on Dictionaries in Python: Operators and Methods of the Dictionary class. A list is an ordered sequence of objects, whereas dictionaries are unordered sets. of an abstract data type, known in computer science as an associative array. Associative arrays consist - like dictionaries of (key, value) pairs, such that � Array list size will increase or decrease dynamically; it can take any size of values from any data type. Dictionary A Dictionary class is a data structure that represents a collection of keys and value pairs of data. The key is identical in a key-value pair and it can have at most one value in the dictionary Example Program

Python2 Tutorial: Dictionaries, Python programs or scripts without lists and dictionaries are nearly inconceivable . A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. a list consisting of the values. items() can be used to create a list consisting of 2-tuples of (key,value)-pairs: >� Here, the list [0..] represents , x^2>3 represents the predicate, and 2*x represents the output expression.. List comprehensions give results in a defined order (unlike the members of sets); and list comprehensions may generate the members of a list in order, rather than produce the entirety of the list thus allowing, for example, the previous Haskell definition of the members of an infinite list.

Dictionaries and strings, Such a dictionary is created by one of the following two statements The temps dictionary has now four text-value pairs, and a print temps yields The keys and values can be extracted as lists from a dictionary: a list of the terms in the polynomial using a list comprehension, and then we feed this list to the sum function. a few scipy functions (like scipy.ndimage.interpolation.geometric_transform) can take pointers c functions arguments avoid having call python callable on each point of input array.in nutshell :define function called my_function somewhere in c modulereturn pycobject&my_function pointer , (optionally) void* pointer pass global data aroundthe related api method pycobject_fromvoidptranddesc, , can

Comments
  • The code you provided works for me, but the result is not what you want: {1: ['1a'], 2: ['2a'], 3: ['3a'], '1': ['1b'], '2': ['2b'], '3': ['3b']}
  • Your code works for me too. The result is {1: ['1a'], 2: ['2a'], 3: ['3a'], '1': ['1b'], '2': ['2b'], '3': ['3b']}
  • It makes no sense to use a list comprehension here.