Joining dictionaries in a for loop - python

I have a simple for loop
for m in my_list:
x = my_function(m)
my_dictionary = {m:x}
my_function() gives me a string. And if I use print my_dictionary at the end i get
{m1: string1}
{m2: string2}
I want to be able to have one dictionary at the end.
I have tried several methods that I found in other threads.
dic = dict(my_dictionary, **my_dictionary)
dic = my_dictionary.copy()
dic.update(my_dictionary)
But overtime I just get the last dictionary instead of all dictionaries.
I wish I could just add them with +, but you can't do that in python

You can use a dict comprehension to create your main dict:
dic = {m : my_function(m) for m in my_list}

Why are you creating separate dictionaries in the first place? Just set the key in an existing dict on each iteration.
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary[m] = x

Maybe I'm missing something, but isn't your problem just that you want a simple, non-nested dictionary, and you keep overwriting it within the loop? In that case, this small change should suffice:
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary[m] = x

You can update the dictionary as opposed to overwrite it each time.
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary.update({m:x})
print my_dictionary

There is no need to recreate a new dictionnary at each loop iteration.
You can either create the dictionnary before and add items to it as you iterate:
my_dict = {}
for m in my_list:
my_dict[m] = my_function(m)
or you can use a dict comprehension:
my_dict = {m:my_function(m) for m in my_list}
or, in python 2:
my_dict = dict((m,my_function(m)) for m in my_list)

Related

Find a value of Key in Json Array - Python

I have a Json array which has key value pairs. I want to get value of a particular key in the list. I don't know at what position the key will be in the array so I cant use the index in the array.
How can I get this please? I have tried something like below code to get value of 'filterB' which is 'val1' but no luck. Thanks.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
w = y['filters']['filterB']
print (w)
w = y['filters']['filterB'] doesn't work because y['filters'] is a list and not dict.
The answer to your question depends on how you want to handle the case of multiple dictionaries inside filters list that have filterB key.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
# all filterB values
filter_b_values = [x['filterB'] for x in y['filters'] if 'filterB' in x.keys()]
# take first filterB value or None if no values
w = filter_b_values[0] if filter_b_values else None
The source of your data (json) has nothing to do with what you want, which is to find the dictionary in y['filters'] that contains a key called filterB. To do this, you need to iterate over the list and look for the item that fulfils this condition.
w = None
for item in y['filters']:
if 'filterB' in item:
w = item['filterB']
break
print(w) # val1
Alternatively, you could join all dictionaries into a single dictionary and use that like you originally tried
all_dict = dict()
for item in y['filters']:
all_dict.update(item)
# Replace the list of dicts with the dict
y['filters'] = all_dict
w = y['filters']['filterB']
print(w) # val1
If you have multiple dictionaries in the list that fulfil this condition and you want w to be a list of all these values, you could do:
y = {"filters":[{"filterA":"All"},{"filterB":"val1"},{"filterB":"val2"}]}
all_w = list()
for item in y['filters']:
if 'filterB' in item:
all_w.append(item['filterB'])
Or, as a list-comprehension:
all_w = [item['filterB'] for item in y['filters'] if 'filterB' in item]
print(all_w) # ['val1', 'val2']
Note that a list comprehension is just syntactic sugar for an iteration that creates a list. You aren't avoiding any looping by writing a regular loop as a list comprehension

How can I make a one line generator expression to generate these two different lists

I am writing a program which parses lists like this.
['ecl:gry', 'pid:860033327', 'eyr:2020', 'hcl:#fffffd', 'byr:1937', 'iyr:2017', 'cid:147', 'hgt:183cm']
I want to turn this list into a dictionary of the key value pairs which I have done here:
keys = []
values = []
for string in data:
pair = string.split(':')
keys.append(pair[0])
values.append(pair[1])
zipped = zip(keys, values)
self.dic = dict(zipped)
print(self.dic)
I know that I can use list comprehension to make one of the lists at a time like this
keys = [s.split(':')[0] for s in data]
values = [s.split(':')[1] for s in data]
This requires two loops so the first code example would be better, but is there a way to generate both lists using one generator with unpacking and then zip the two together?
l = ['ecl:gry', 'pid:860033327', 'eyr:2020', 'hcl:#fffffd',
'byr:1937', 'iyr:2017', 'cid:147', 'hgt:183cm']
dict(e.split(':') for e in l)
I did it like this:
self.dic = {}
for e in data:
k, v = e.split(':')
self.dic[k] = v
You can dict comprehension it easily:
your_dict = {x.split(':')[0]: x.split(':')[1] for x in data}
You can also prevent from using split two times and use generator:
your_dict = dict(x.split(':') for x in data)
Which seems even cleaner...

Pythonic way of adding items to a dict of lists

I use this snippet pretty often:
d = {}
for x in some_list:
y = some_func(x) # can be identity
if y in d:
d[y].append(another_func(x))
else:
d[y] = [another_func(x)]
Is this the most pythonic way of doing this or there's a better way? I use Python 3.
you can try
from collections import defaultdict
d = defaultdict(list)
for x in some_list:
d[some_func(x)].append(another_func(x))
The defaultdict is a dictionary option that you init it with the type that you would like to assign in case the key that you are looking for not exists in the keys of the dictionary.
In this case, each time that you will call d if the key doesn't exist it will create an empty list.

how to create a new dictionary using for loop in python [duplicate]

This question already has answers here:
How do you create different variable names while in a loop? [duplicate]
(9 answers)
Closed 3 years ago.
suppose I have lists of strings like this
list1 = ["x","y","z"]
so how can create empty dictionaries like x = {}, y = {} and z = {} by iteration
Following method does nothing:
for i in list1:
i = dict()
As recommended do not dynamiclly create variable from strings
This said, you may store this in a dict to store, then associate an empty dict for each key
result = {}
for idx in list1:
result[idx] = {}
print(result)
# {'x': {}, 'y': {}, 'z': {}}
Check out the following code:
list1 = ["x","y","z"]
for i in list1:
globals()[i] = dict()
This will give you:
x = {}
y = {}
z = {}
To check the output and its types you can do the following:
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
You can use the built-in exec function.
For example, exec("x=3") creates the x variable, assigning to it the value 3.
Your specific example can be solved like this:
for var in list1:
exec(var + "={}")
This dynamic creation of variable names is not advised most of the time.
Check Creating dynamically named variables from user input.
I am not sure what you are attempting to do but would this is a possible approach.
list1 = ["x","y","z"]
d = {}
for i in list1:
d[i] = {}
You would get a dict with an empty dict inside for each of your strings.
Here is one solution :
for i in list1:
locals()[i] = dict()

how to iterate values of perticular keys in python dictionary?

I have something like this,
newlist = []
list =['a','b','c','d','e']
dict = {'a':['a','a1','a2','a3'],'b':['b','b1','b2','b3'],.....'e':['e','e1','e2','e3']
}
I have tried like this,
for listval in list:
newlist.append(dict[listval]].values())
But am not getting expected result,my expectation is,
newlist = [['a','a1','a2','a3'],['b','b1','b2','b3'],....,['e','e1','e2','e3']]
new_list = [the_dict[k] for k in the_list]
or if some keys might be missing:
new_list = [the_dict[k] for k in the_list if k in the_dict]
Try this - :
newlist = [dict.get(i) for i in list if dict.has_key(i)]
It will handle key exists and other errors.
Above will work for you.. :)
You can use map if you know for sure that all the keys will be in the list.
list1 =['a','b','c','d','e']
dict1 = {'a':['a','a1','a2','a3'],'b':['b','b1','b2','b3'],'c':['c','c1','c2','c3'],'d':['d','d1','d2','d3'],'e':['e','e1','e2','e3']}
newlist = map(dict1.get, list1)

Categories

Resources