Python - Creating a list of dictionaries - python

I wanted to create a list of dictionaries in python. The usual way of creating a list worked for me. That is mylist = [{1:1},{2:2}]
However, when I tried creating it using a comprehension over range() function, mylist = [a:a for a in range(10)] I get syntax error.
But to my surprise, if I construct a set in the same manner, it works as expected. myset = {a:a for a in range(10)}
May I know why this is so? I am using Python3

I think you want something like this:
mylist = [{a:a} for a in range(10)]
You forgot about { and }.
In the second example, your myset is a dict, not a set:
In [8]: type(myset)
Out[8]: dict
In this example, { and } denote dictionary comprehension, not set comprehension.

You're missing a dictionary creation in your list comprehension:
mylist = [{a:a} for a in range(10)]

Related

Converting nested lists to dictionary with self generated keys

My list of lists looks like this:
my_list = [[sub_list_1],[sub_list_2],...,[sub_list_n]]
Desired output
my_dict[1] = [sub_list_1]
my_dict[2] = [sub_list_2]
my_dict[n] = [sub_list_n]
I want the keys for the dictionary to be generated on their own. How can this be achieved in a pythonic way?
I look at certain questions like
Converting list of lists in dictionary python
Python: List of lists to dictionary
Converting nested lists to dictionary
but they either provide a list of keys or focus on using some information from the lists as keys.
Alternatively, I tried making a list of keys this way:
my_keys = list(range(len(my_list)))
my_dict = dict(zip(my_keys,my_list)
and it works but, this does not:
my_dict = dict(zip(list(range(len(my_list))),my_list))
This gives me a syntax error.
So in summary:
Is there a way to generate a dictionary of lists without explicitly providing keys?, and
Why does the combined code throw a syntax error whereas the two step code works?
I would recommend to use a dict comprehension to achieve what you want like in here, moreover I tried your implementation and haven't faced any issues (more details are more than welcome):
my_list = [["sub_list_1"],["sub_list_2"],["sub_list_3"]]
my_dict = dict(zip(list(range(len(my_list))),my_list))
alternative_dict = {iter:item for iter,item in enumerate(my_list)}
print("yours : " + str(my_dict))
print("mine : " + str(alternative_dict))
output:
yours : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
mine : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
Your syntax error is caused by your variable name try. try is allready a name in python. see try/except
This should do it
my_dict = {my_list.index(i) + 1: i for i in my_list}
Notice that I have added +1 to start at the key 1 instead of 0 to match your expectations
I received no error message when running your code:
>>> my_list = [["hello1"], ["hello2"]]
>>> my_dict = dict(zip(list(range(len(my_list))), my_list))
>>> my_dict
{1: ['hello1'], 2: ['hello2']}
You can create a dict of lists from a list of lists using a dict comprehension:
my_dict = {i: sub_list for i, sub_list in enumerate(my_list)}

Union with nested list/multiple for loops

I have a dictionary like so:
myDict = {'items':
[{'names': [{'longName1', 'shortName1'},
{'shortName2', 'longName2'}]},
{'names': [{'longName3', 'shortName3'},
{'shortName4', 'longName4'}]}]}
Attempting to get the keys (i.e. shortName) in a set Pythonically. I have the following statement, but it's complaining that i isn't defined. What am I doing wrong?
shortNames = set().union(*(j.values() for j in i["names"] for i in myDict["items"]))
Expected result:
set(['shortName1', 'shortName2', 'shortName3', 'shortName4'])
You are accessing i["names"] before i is defined by i in myDict["items"].
You have to swap the for loops:
set().union(*[j for i in myDict["items"] for j in i["names"]])
See, it is not advisable to chain list comprehensions just for the sake of brevity. Since you are asking, one way would be:
>>> from itertools import chain
>>> {j for j in (chain.from_iterable(sum([i['names'] for i in myDict['items']],[]))) if j.startswith('short')}
{'shortName1', 'shortName2', 'shortName3', 'shortName4'}
Your method could not work:
As dacx mentioned.
j.values() would not give you shortNames as those are inside sets not dicts, and sets do not have .values() method.
OR:
>>> {j for j in set().union(*(set().union(*i['names']) for i in myDict['items'])) if j.startswith('short')}
{'shortName1', 'shortName2', 'shortName3', 'shortName4'}

How to form a list from queried data?

I have the following code:
s = (f'{item["Num"]}')
my_list = []
my_list.append(s)
print(my_list)
As you can see i want this to form a list that i will then be able to store under my_list, the output from my code looks like this (this is a sample from around 2000 different values)
['01849']
['01852']
['01866']
['01883']
etc...
This is not what i had in mind, i want it to look like this
[`01849', '01852', '01866', '01883']
Has anyone got any suggestions on what i do wrong when i create the list? Thanks
You can fix your problem and represent this compactly with a list comprehension. Assuming your collection is called items, it can be represented as such, without the loop:
my_list = [f'{item["Num"]}' for item in items]
You should first initialize a list here, and then use a for-loop to populate it. So:
my_list = []
for values in range(0, #length of your list):
s = (f'{item["Num"]}')
my_list.append(s)
print(my_list)
Even better, you can also use a list comprehension for this:
my_list = [(f'{item["Num"]}') for values in range(0, #length of your list)]

Python, Combining lists within a dict

Is it possible to combine lists in a dict to a new key?
For example, i have a dict setup
ListDict = {
'loopone': ['oneone', 'onetwo', 'onethree'],
'looptwo': ['twoone', 'twotwo', 'twothree'],
'loopthree': ['threeone', 'threetwo', 'threethree']}
I want a new key called 'loopfour' which contains the lists from 'loopone', 'looptwo', and 'loopthree'
So its list would look like
['oneone', 'onetwo', 'onethree', 'twoone', 'twotwo', 'twothree', 'threeone', 'threetwo', 'threethree']
and can be called using ListDict['four'] and return the combined list
Just use two for clauses in a list comprehension. Note however, dictionaries are not ordered so the resulting list can come out in a different order than they were originally put in the dictionary:
>>> ListDict['loopfour'] = [x for y in ListDict.values() for x in y]
>>> ListDict['loopfour']
['oneone', 'onetwo', 'onethree', 'twoone', 'twotwo', 'twothree', 'threeone', 'threetwo', 'threethree']
If you want it ordered then:
>>> ListDict['loopfour'] = [x for k in ['loopone', 'looptwo', 'loopthree'] for x in ListDict[k]]
>>> ListDict['loopfour']
['oneone', 'onetwo', 'onethree', 'twoone', 'twotwo', 'twothree', 'threeone', 'threetwo', 'threethree']

python for loop expression of iterator

I have a for loop in which I use the iterator always in the same manner, like this
for dict in mylist:
var = dict['prop']
var2 = f( dict['prop'] )
...
This is clumsy. The only alternatives I can think of:
local variable
wrapping the mylist in a list comprehension. But that seems overkill and is probably inefficient
Any better way?
One map call would work to give you a list of tuples of values:
listOfTuples = map(lambda x: (dict['prop'], f(dict['prop']), myList)
Or if you want two separate lists of values:
[varList, var2List] = zip(*zip(listOfTuples))

Categories

Resources