I have dictionary in the following format:
dictionary = {'key' : ('value', row_number, col_number)}
I want that dictionary converted to below format:
converted_dict = {'key' : {'row':row_number, 'col':col_number}}
By using the following code i am getting below error
dict_list = [(key, dict([('row',value[1]), ('column',value[2])])) for
key, value in cleaned_dict]
converted_dict = dict(dict_list)
ValueError: too many values to unpack (expected 2)
I don't quite understand why you try to convert the dictionary to list when what you want is in fact dict. It seems you don't understand how to do dict comprehension. Try this approach:
converted_dict = {
key: {'row': value[1], 'column': value[2]} for key, value in cleaned_dict.items()
}
Also note that if you want to iterate over both the keys and the values in a dictionary you should call dictionary.items() (like in the code above)
You could use a dictionary comprehension:
dictionary = {'key' : ('value', 'row_number', 'col_number')}
>>> {k: {'row': row, 'col': col} for k, (_, row, col) in dictionary.items()}
{'key': {'row': 'row_number', 'col': 'col_number'}}
Iterating through dictionary only return nd no need of extra steps for convert list into dictionary. key,
So here we need pair of key and values so we need to use dict.items,
In [6]: lst = {'a':(0,1),'b':(2,1)}
In [7]: converted_dict = dict((key, dict([('row',value[0]), ('column',value[1])])) for key, value in lst.items())
Out[7]: {'a': {'column': 1, 'row': 0}, 'b': {'column': 1, 'row': 2}}
...and yet another dict-comprehension.
converted_dict = {k : dict(zip(('row', 'column'), v[1:])) for k, v in dictionary.items()}
which for:
dictionary = {'a' : ('value', 1, 2), 'b' : ('value', 0, 0)}
returns:
{'a': {'row': 1, 'column': 2}, 'b': {'row': 0, 'column': 0}}
The only thing wrong with your code is that it is missing the .items()1. It had to be:
dict_list = [... for key, value in cleaned_dict.items()]
1. If you are using Python 2 you need .iteritems() instead.
Related
I have a dict like below
d = {"a":0,"b":1,"c":2}
I need to get only this in my output dict
out = {"b":1}
tried converting the dict to list and accessing the index 1, but it gives me tuples.
Is there any workaround for this
print(list(d.items())[1])
("b",1)
You could do out = {elem:d[elem] for idx,elem in enumerate(d) if idx in [0,1]} to select the indexes in [0,1] but dict([list(d.items())[1]]), as metioned by #Anetropic, works fine as well.
What is the source of your key value? If you want to get all the items in dictionary from a key container:
>>> keys = ['b', 'c']
>>> {key: d[key] for key in keys}
{'b': 1, 'c': 2}
If you just want to get it in order from d.items():
>>> from itertools import islice
>>> dict(islice(d.items(), 1, 3))
{'b': 1, 'c': 2}
My code is
index = 0
for key in dataList[index]:
print(dataList[index][key])
Seems to work fine for printing the values of dictionary keys for index = 0. However, I can't figure out how to iterate through an unknown number of dictionaries in dataList.
You could just iterate over the indices of the range of the len of your list:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for index in range(len(dataList)):
for key in dataList[index]:
print(dataList[index][key])
or you could use a while loop with an index counter:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
index = 0
while index < len(dataList):
for key in dataList[index]:
print(dataList[index][key])
index += 1
you could even just iterate over the elements in the list directly:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for key in dic:
print(dic[key])
It could be even without any lookups by just iterating over the values of the dictionaries:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for val in dic.values():
print(val)
Or wrap the iterations inside a list-comprehension or a generator and unpack them later:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
print(*[val for dic in dataList for val in dic.values()], sep='\n')
the possibilities are endless. It's a matter of choice what you prefer.
You can easily do this:
for dict_item in dataList:
for key in dict_item:
print(dict_item[key])
It will iterate over the list, and for each dictionary in the list, it will iterate over the keys and print its values.
use=[{'id': 29207858, 'isbn': '1632168146', 'isbn13': '9781632168146', 'ratings_count': 0}]
for dic in use:
for val,cal in dic.items():
print(f'{val} is {cal}')
def extract_fullnames_as_string(list_of_dictionaries):
return list(map(lambda e : "{} {}".format(e['first'],e['last']),list_of_dictionaries))
names = [{'first': 'Zhibekchach', 'last': 'Myrzaeva'}, {'first': 'Gulbara', 'last': 'Zholdoshova'}]
print(extract_fullnames_as_string(names))
#Well...the shortest way (1 line only) in Python to extract data from the list of dictionaries is using lambda form and map together.
"""The approach that offers the most flexibility and just seems more dynamically appropriate to me is as follows:"""
Loop thru list in a Function called.....
def extract_fullnames_as_string(list_of_dictionaries):
result = ([val for dic in list_of_dictionaries for val in
dic.values()])
return ('My Dictionary List is ='result)
dataList = [{'first': 3, 'last': 4}, {'first': 5, 'last': 7},{'first':
15, 'last': 9},{'first': 51, 'last': 71},{'first': 53, 'last': 79}]
print(extract_fullnames_as_string(dataList))
"""This way, the Datalist can be any format of a Dictionary you throw at it, otherwise you can end up dealing with format issues, I found. Try the following and it will still works......."""
dataList1 = [{'a': 1}, {'b': 3}, {'c': 5}]
dataList2 = [{'first': 'Zhibekchach', 'last': 'Myrzaeva'}, {'first':
'Gulbara', 'last': 'Zholdoshova'}]
print(extract_fullnames_as_string(dataList1))
print(extract_fullnames_as_string(dataList2))
Another pythonic solution is using collections module.
Here is an example where I want to generate a dict containing only 'Name' and 'Last Name' values:
from collections import defaultdict
test_dict = [{'Name': 'Maria', 'Last Name': 'Bezerra', 'Age': 31},
{'Name': 'Ana', 'Last Name': 'Mota', 'Age': 31},
{'Name': 'Gabi', 'Last Name': 'Santana', 'Age': 31}]
collect = defaultdict(dict)
# at this moment, 'key' becomes every dict of your list of dict
for key in test_dict:
collect[key['Name']] = key['Last Name']
print(dict(collect))
Output should be:
{'Name': 'Maria', 'Last Name': 'Bezerra'}, {'Name': 'Ana', 'Last Name': 'Mota'}, {'Name': 'Gabi', 'Last Name': 'Santana'}
There are multiple ways to iterate through a list of dictionaries. However, if you are into Pythonic code, consider the following ways, but first, let's use data_list instead of dataList because in Python snake_case is preferred over camelCase.
Way #1: Iterating over a dictionary's keys
# let's assume that data_list is the following dictionary
data_list = [{'Alice': 10}, {'Bob': 7}, {'Charlie': 5}]
for element in data_list:
for key in element:
print(key, element[key])
Output
Alice 10
Bob 7
Charlie 5
Explanation:
for element in data_list: -> element will be a dictionary in data_list at each iteration, i.e., {'Alice': 10} in the first iteration,
{'Bob': 7} in the second iteration, and {'Charlie': 5}, in the third iteration.
for key in element: -> key will be a key of element at each iteration, so when element is {'Alice': 10}, the values for key will be 'Alice'. Keep in mind that element could contain more keys, but in this particular example it has just one.
print(key, element[key]) -> it prints key and the value of element for key key, i.e., it access the value of key in `element.
Way #2: Iterating over a dictionary's keys and values
# let's assume that data_list is the following dictionary
data_list = [{'Alice': 10}, {'Bob': 7}, {'Charlie': 5}]
for element in data_list:
for key, value in element.items():
print(key, value)
The output for this code snippet is the same as the previous one.
Explanation:
for element in data_list: -> it has the same explanation as the one in the code before.
for key, value in element.items(): -> at each iteration, element.items() will return a tuple that contains two elements. The former element is the key, and the latter is the value associated with that key, so when element is {'Alice': 10}, the value for key will be 'Alice', and the value for value will be 10. Keep in mind that this dictionary has only one key-value pair.
print(key, value) -> it prints key and value.
As stated before, there are multiple ways to iterate through a list of dictionaries, but to keep your code more Pythonic, avoid using indices or while loops.
had a similar issue, fixed mine by using a single for loop to iterate over the list, see code snippet
de = {"file_name":"jon","creation_date":"12/05/2022","location":"phc","device":"s3","day":"1","time":"44692.5708703703","year":"1900","amount":"3000","entity":"male"}
se = {"file_name":"bone","creation_date":"13/05/2022","location":"gar","device":"iphone","day":"2","time":"44693.5708703703","year":"2022","amount":"3000","entity":"female"}
re = {"file_name":"cel","creation_date":"12/05/2022","location":"ben car","device":"galaxy","day":"1","time":"44695.5708703703","year":"2022","amount":"3000","entity":"male"}
te = {"file_name":"teiei","creation_date":"13/05/2022","location":"alcon","device":"BB","day":"2","time":"44697.5708703703","year":"2022","amount":"3000","entity":"female"}
ye = {"file_name":"js","creation_date":"12/05/2022","location":"woji","device":"Nokia","day":"1","time":"44699.5708703703","year":"2022","amount":"3000","entity":"male"}
ue = {"file_name":"jsdjd","creation_date":"13/05/2022","location":"town","device":"M4","day":"5","time":"44700.5708703703","year":"2022","amount":"3000","entity":"female"}
d_list = [de,se,re,te,ye,ue]
for dic in d_list:
print (dic['file_name'],dic['creation_date'])
I have a for loop which is going through multiple dictionaries and adding the values under common keys. The input dictionary has keys that are strings and values that are int's. For some reason its adding the values as lists of one value (e.g. {"01":[12],[44]}). I want it to add the int on its own but cant get that working for some reason. I'm using the code below, is there something i am missing ?
dw = defaultdict()
dw = {}
for key, value in listb.items():
dw[key].append(value)
If you want to forgo all good practice and not use defaultdict(list), you can use setdefault and call it every single time you choose to add a value. This is inefficient and not idiomatic, but it will work.
In [1]: from collections import defaultdict
In [2]: a = defaultdict(list)
In [3]: b = {}
In [4]: a[1].append(1)
In [5]: b.setdefault(1, []).append(1)
In [6]: a
Out[6]: defaultdict(list, {1: [1]})
In [7]: b
Out[7]: {1: [1]}
In [8]:
As long as the values in the dicts are ints (not lists):
dw = {}
for key, value in listb.items():
try: # Key exists in dictionary and value is a list
dw[key].append(value)
except KeyError: # Key does not yet exist in dictionary
dw[key] = value
except AttributeError: # Key exist in dictionary and value is not a list
dw[key] = [dw[key], value]
If you mean to add key/value pairs to the dictionary (and not append to an array), it's:
for key, value in listb.items():
dw[key] = value
EDIT: or is it something like this you're after?
listb = {'1': 3, '2': 5}
dw = {'1': 5, '2': 9}
for key, value in listb.items():
if key not in dw.keys():
dw[key] = []
else:
dw[key] = [dw[key]]
dw[key].append(value)
which gives dw = {'2': [9, 5], '1': [5, 3]}
If you have a list like listb = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4, 'c': 5}, {'b': 1}], you can try this:
dw = {}
for d in listb:
for k, v in d.items():
if k in dw:
if isinstance(dw[k], list):
dw[k].append(v)
elif isinstance(dw[k], int):
dw[k] = [dw[k], v]
else:
dw[k] = v
print(dw)
{'a': [1, 3], 'b': [2, 4, 1], 'c': 5}
>>>
I have a dict that looks like this:
{'Item1': [{'Name1': 3}, {'Name2': 4}, {'Name1':7}],
'Item2': [{'Name7': 44}, {'Name2': 3}, {'Name6':9}, {'Name6':2}]
}
I want to combine dictionaries in the list attached to the key such that if there are multiple dicts with the same key, I can combine them (sum) and leave the others as they are.
The output would look like:
{'Item1': [{'Name1': 10}, {'Name2': 4}],
'Item2': [{'Name7': 44}, {'Name2': 3}, {'Name6': 11}]
}
I can't figure out how to do this in Python elegantly with a list/dict comprehension.
This uses collections.Counter. It is about the most elegant I could come up with, because of the slightly convoluted structure of your input - a list of 1-length dictionaries would indeed be better implemented as a single dictionary, as the comments suggest. This is also what my code transforms it to, although I have provided some more possible tranformations if you really direly need the old data structure. If you do, I would recommend using tuples as your key-value pairs rather than just single-length dicts, as seen in tuple_output. I recommend you use output or dict_output.
from collections import Counter
d = {'Item1': [{'Name1': 3}, {'Name2': 4}, {'Name1':7}], 'Item2': [{'Name7': 44}, {'Name2': 3}, {'Name6':9}, {'Name6':2}] }
output = {}
for k, v in d.items():
c = Counter()
for sub_dict in v:
c.update(sub_dict)
output[k] = c
dict_output = {k: dict(v) for k, v in output.items()}
tuple_output = {k: v.most_common() for k, v in output.items()}
dict_list_output = {k: [{a: b} for a, b in v.most_common()] for k, v in output.items()}
print(output)
#{'Item1': Counter({'Name1': 10, 'Name2': 4}), 'Item2': Counter({'Name7': 44, 'Name6': 11, 'Name2': 3})}
print(dict_output)
#{'Item1': {'Name1': 10, 'Name2': 4}, 'Item2': {'Name7': 44, 'Name2': 3, 'Name6': 11}}
print(tuple_output)
#{'Item1': [('Name1', 10), ('Name2', 4)], 'Item2': [('Name7', 44), ('Name6', 11), ('Name2', 3)]}
print(dict_list_output)
#{'Item1': [{'Name1': 10}, {'Name2': 4}], 'Item2': [{'Name7': 44}, {'Name6': 11}, {'Name2': 3}]}
Of course, if you change the starting data structure altogether, it will become a lot easier to manage. If you use a dictionary from strings to Counters, you can use the Counter interface to easily update it (refer to the link)
Edit:
Just for fun, done in one line:
results = {item: reduce(lambda a, b: [a, a.update(b)][0], names, Counter()) for item, names in d.items()}
It was inspired by yours, except this only builds one Counter instance (given as the initial value for reduce) per list. Also, a little bit of a golfy trick is required to reduce properly, as Counter.update is in place. If you're reading this, you probably shouldn't use it, and instead build a data structure with Counters or dicts from the start, as mentioned earlier.
Assuming you do want to collapse this into a single dict vs list[dict] then you can do this without any additional modules with a couple of simple for loops:
In []:
r = {}
for k, ds in data.items():
s = {}
for d in ds:
for v, c in d.items():
s[v] = s.get(v, 0) + c
r[k] = s
r
Out[]:
{'Item1': {'Name1': 10, 'Name2': 4}, 'Item2': {'Name2': 3, 'Name6': 11, 'Name7': 44}}
As some seem to be going for one liners:
In []:
import itertools as it
from collections import Counter
{k: dict(Counter(v for v, c in it.chain.from_iterable(d.items() for d in ds))
for _ in range(c)) for k, ds in data.items()}
Out[]:
{'Item1': {'Name1': 10, 'Name2': 4}, 'Item2': {'Name2': 3, 'Name6': 11, 'Name7': 44}}
It occurred to me just a few minutes after posting the question.
This is what I did:
from operator import add
from collections import Counter
results = {}
for item, names in d.items():
result[item] = (reduce(add, (Counter(name) for name in names)))
As the above comments and answers suggest, I am better off using a 1-length dictionary instead of having to combine several later. Still, leaving the answer out here for anyone that needs it.
Can also try with defaultdict
from itertools import chain
from collections import defaultdict
d_new = {}
for k, v in d.items():
d_dict = defaultdict(int)
for k1, v1 in chain(*[ i.items() for i in v ]) :
d_dict[k1]+= v1
d_new[k] = dict(d_dict)
print (d_new)
Output:
{'Item1': {'Name1': 10, 'Name2': 4}, 'Item2': {'Name7': 44, 'Name2': 3, 'Name6': 11}}
chain(*[ i.items() for i in v ]) will flatten the list of dicts into list of items
Converts
[{'Name1': 3}, {'Name2': 4}, {'Name1':7}]
to
[('Name1', 3), ('Name2', 4), ('Name1', 7)]
defaultdict(int) is used to add the values of dict with same keys
I am new at python and here. I need to create N new dictionaries based on N keys from an original dictionary.
Lets say I have an OriginalDict {a:1, b:2, c:3, d:4, e:5, f:6} I need to create 6 new dictionaries having as keys (new keys are same) the value of the original. Something like that:
Dict1 {Name:a,...}, Dict2 {Name:b,...}, Dict3 {Name:c,...}.....
Dict6 {Name:f...}
This is my code:
d = {}
for key in OriginalDict:
d['Name'] = key
I got a new dictionary but only for the last key.
print d
{Name:f}
I guess cos' last value in a dictionary overrides the previous one if the keys are the same
please advise... :)
If, for example, we put all those dicts in a list, we can use this comprehensions
dicts = [{'Name': k} for k in OriginalDict]
Let's try it out
>>> OriginalDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
>>> dicts = [{'Name': k} for k in OriginalDict]
>>> dicts
[{'Name': 'd'}, {'Name': 'c'}, {'Name': 'a'}, {'Name': 'b'}, {'Name': 'e'}, {'Name': 'f'}]
The statement 6 new dictionaries having as keys (new keys are same) the value of the original seems to contradict your example, at least to me.
In such case we can do
dicts = [{v: k} for k, v in OriginalDict.items()]
Let's try it out:
>>> dicts = [{v: k} for k, v in OriginalDict.items()]
>>> dicts
[{4: 'd'}, {3: 'c'}, {1: 'a'}, {2: 'b'}, {5: 'e'}, {6: 'f'}]
In python 3.x:
for key in OriginalDict.keys():
d = {}
d ['Name'] = key
This will give you a new Dictionary for every key of the Original one. Now, you could save them inside a list or inside another dictionary like:
New_Dicts = []
for key in OriginalDict.keys():
d = {}
d ['Name'] = key
New_Dicts.append(d)
Or,
New_Dicts = {}
for i,key in enumerate(OriginalDict.keys()):
d = {}
d ['Name'] = key
New_Dicts[i] = d
I think you want to create a function which is a generator, then call that function passing in the dictionary and then yielding your new ones:
orig = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
def make_sub_dictionaries(big_dictionary):
for key, val in big_dictionary.iteritems():
yield {'name': key, 'val': val }
# if you want them one by one, call next
first = make_sub_dictionaries(orig).next()
print first
# if you want all of them
for d in make_sub_dictionaries(orig):
print str(d)
# do whatever stuff you need to do
One method is as follows:
OriginalDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
newDicts = [{'Name':v} for k,v in enumerate(OriginalDict.values())]
which will give you
>>> newDicts
[{'Name': 1}, {'Name': 3}, {'Name': 2}, {'Name': 5}, {'Name': 4}, {'Name': 6}]
First of all, this won't keep the order. You need to use OriginalDict to preserve the order.
my_dict={'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
j=0
for key, value in my_dict.iteritems():
j +=1
exec("Dict%s = %s" % (j,{key:value}))
Now when you type.
>>> print Dict1
{'a':1}
>>> print Dict2
{'c':3}