I'm trying to create a dictionary of the form:
{: [ , {}]}
For example:
d = {term: [number, {number1: number2}]}
I tried to create the dictionary inside but I'm new and I couldn't understand how it's possible. The problem is that I want the form of d and I want to update number or the dictionary that contains number1 as key and number2 as value when finding term.
So the question is:
Is it possible to create a dictionary like d ? And if so, how can I access term, number and the inside dictionay?
d = {"term": [5, {6: 7}]}
The key's value is a list:
d["term"]
[5, {6: 7}]
The list 's 1st element:
d["term"][0]
5
The list 's second element is a dictionary:
d["term"][1]
{6: 7}
The value of the dictionary's key '6' is 7:
d["term"][1][6]
7
Edit:
Some examples for modification:
d = {"term": [5, {6: 7}]}
d["term"].append(10)
print(d)
Out: {'term': [5, {6: 7}, 10]}
l=d["term"]
l[0]=55
print(d)
Out: {'term': [55, {6: 7}, 10]}
insidedict=l[1]
print(insidedict)
{6: 7}
insidedict[66]=77
print(d)
{'term': [55, {6: 7, 66: 77}, 10]}
Sure, just define it as you have:
d = {'term': [5, {6: 7}]}
Since your dictionary has just one key, you an access the key via:
key = next(iter(d))
You can then access the value 5 via a couple of ways:
number = d[key][0]
number = next(iter(d.values()))[0]
Similarly, you can access the inner dictionary via either:
inner_dict = d[key][1]
inner_dict = next(iter(d.values()))[1]
And repeat the process for inner_dict if you want to access its key / value.
Related
I have a list [{"a":11, "b":2}, {"a":12, "b":2}, {"a":13, "b":3}, {"a":14, "b":4}]
I want to combine values of a based on values of b
I want output as [{'a':[11, 12], 'b':2}, {'a':[13], 'b':3}, {'a':[14], 'b':4}]
I have tried [{ k:list(set([d[k] for d in a])) for k in a[0] } for i in a]
You can create an intermediary dict to map values of b to a sub-list of the values of a, and then use a list comprehension that outputs the items of the intermediary dict as a dict with keys as 'b' and values as 'a':
mapping = {}
for d in lst:
mapping.setdefault(d['b'], []).append(d['a'])
[{'a': v, 'b': k} for k, v in mapping.items()]
This returns:
[{'a': [11, 12], 'b': 2}, {'a': [13], 'b': 3}, {'a': [14], 'b': 4}]
I want to create a dictionary from a given list, nesting elements as shown below. For instance, given:
lst = range(1, 11)
how do I create a function to create a nested dictionary from this list:
dic = {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
Reverse your list (or better range object). Take the last (now first) element as start value and create a new dict in each iteration through the rest of the reversed list:
>>> r = reversed(range(1, 11))
... d = next(r)
... for x in r:
... d = {x: d}
... d
...
{1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
You could use functools.reduce.
import functools
lst = range(1, 11)
functools.reduce(lambda x, y: {y: x}, reversed(lst))
# {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
You can build it from inside out:
result = {9: 10}
for i in range(8, 0, -1):
temp = {i: result}
result = temp
print(result)
# outputs {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
Start from the innermost value, working outward.
At each step, use the previous step's dict as the new val.
def nest_dict(lst):
my_dict = lst[-1]
for val in lst[-2::-1]:
my_dict = {val: my_dict}
return my_dict
print nest_dict(range(1, 11))
Output:
{1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
my_list = [{0: 0}, {1: 4.2}, {2: 3.7}, {3: 5.0}, {4: 4.0}, {5: 3.3}, {6: 4.3}, {7: 4.0}, {8: 3.9}, 0, {10: 4.0}]
What I want my program to do is go through the list, record the highest value (as in the value from a key-value pair) once it's scanned through the entire thing, append that key-pair value to a new list, remove that key-pair value from the original list [my_list], and repeat the process twice more. So the desired output would look like this:
desired output: [{3: 5.0},{6: 4.3},{1: 4.2}]
I'm not sure how to achieve the desired output.
I'm assuming that the single integer in your my_list is a typo.
Use the heapq module to get the three largest items. This has slightly better complexity and memory efficiency than sorting the whole list and then extracting the last three elements.
>>> from heapq import nlargest
>>> my_list = [{0: 0}, {1: 4.2}, {2: 3.7}, {3: 5.0}, {4: 4.0}, {5: 3.3}, {6: 4.3}, {7: 4.0}, {8: 3.9}, {10: 4.0}]
>>> nlargest(3, my_list, key=lambda d: d.values()[0])
[{3: 5.0}, {6: 4.3}, {1: 4.2}]
The key function specifies the criterion by which the items from your list are to be ordered, it simply fetches the only value any individual dictionary has.
I'm trying to achieve the following:
given
a = [{'val': 10, 'count': 1}]
b = [{'val': 10, 'count': 4}, {'val': 20, 'count': 2}]
I would like to get
output = [{'val': 10, 'count': 5}, {'val': 20, 'count': 2}]
That is, merging 2 lists of dicts according to val: if in 2 dict instances the val is the same, combine by summing the counts, otherwise keep 2 instances.
By the way, performance is an issue, so an elegant and fast solution is preferred.
Thanks!
Based on #Brionius idea you can manipulate you data using Counter and List comprehension:
We will take the data and create a dict that we can use easily with Counter, then we can add up the data and finally revert back to the format we want(your original format).
from collections import Counter
a = [{'val': 10, 'count': 1}]
b = [{'val': 10, 'count': 4}, {'val': 20, 'count': 2}]
c = Counter()
[c.update({d['val']:d['count']}) for d in a + b]
print [{'val': k, 'count': v} for k, v in c.iteritems()]
Output:
[{'count': 5, 'val': 10}, {'count': 2, 'val': 20}]
If you're willing and able to change your data structure to something a little simpler, like this:
a = {10:1}
b = {10:4, 20:2}
Then you can easily use Counter:
from collections import Counter
c = Counter()
c.update(a)
c.update(b)
print dict(c)
# Result:
# {10: 5, 20: 2}
I have a python list which contains dictionaries and I want to make a new list which contain dictionaries with unique keys and associated list values like below:
Input:
[{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]
Output:
[{1:[2,3,3]},{2:[2,1]}]
Thanks in advance.
How about:
input = [{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]
r = {}
for d in input:
# (assumes just one key/value per dict)
((x, y),) = d.items()
r.setdefault(x, []).append(y)
print [ {k: v} for (k, v) in r.items() ]
Result:
[{1: [2, 3, 3]}, {2: [2, 1]}]
[update]
just curious : Can you explain whats going on in ((x, y),) = d.items() and r.setdefault(x, []).append(y) ? – damned
First the ((x, y),) = d.items():
at this point, d will be an element from input, like {1: 2}
d.items() will be something analogous to [(1, 2)]
in order to unpack 1 and 2 into x and y, we need the extra , (otherwise the interpreter will think the outer parenthesis are doing grouping instead of defining a single element tuple)
The r.setdefault(x, []).append(y) is analogous to:
if not r.has_key(x):
r[x] = []
r[x].append(y)
Trick is to use dict.setdefault to start off a list and append to it:
input = [{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]
output = {}
for d in input:
for k,v in d.items():
output.setdefault(k, []).append(v)
# output contains {1: [2, 3, 3], 2: [2, 1]}
output=[{k:v} for k,v in output.items()]
# output contains [{1: [2, 3, 3]}, {2: [2, 1]}]
What setdefault does is return either the existing list keyed by 'k', or if that key does not exist in the dictionary, it creates a new entry for that key with the second argument and returns that. Either way it returns the list whether it was pre-existing or new, so that you can then append to it.
>>> lis=[{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]
>>> new_lis=[{}]
>>> for x in lis:
for y in x:
if y in new_lis[0]:
new_lis[0][y].append(x[y])
new_lis[0][y].sort()
else :new_lis[0][y]=[x[y]]
>>> new_lis
[{1: [2, 3, 3], 2: [1, 2]}]
>>> data = [{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]
...
... from itertools import groupby
...
... keyFn = lambda x: x.keys()[0]
...
... [{k: [i.values()[0] for i in g]} for k, g in groupby(sorted(data, key=keyFn), keyFn)]
0: [{1: [2, 3, 3]}, {2: [2, 1]}]
output = []
for b in a:
added = 0
i = 0
for c in output:
if b.keys()[0] in c.keys():
output[i][b.keys()[0]].append(b[b.keys()[0]])
added = 1
i += 1
if not added:
output.append({b.keys()[0]: [b[b.keys()[0]]]})