I have several dictionaries:
a["size"] = 12
b["size"] = 10
c["size"] = 11
I need the variable name (a,b or c) with the biggest "size" entry --> How would you implement it? I coud do it with a few if statements. But is there an easier way? It would be easy (with max(..)) if I would need the biggest number.
>>> a = {'size': 12}
>>> b = {'size': 10}
>>> c = {'size': 11}
>>> l = locals()
>>> max("abc", key=lambda x: l[x]['size'])
'a'
Use code below to get dict variable name with biggest size, without knowing names of your variables:
items = locals()
biggest = 0
a = {'size': 0}
b = {'size': -1}
c = {'size': 5}
d = {'size': 10}
e = {'size': 20}
for key in items.keys():
if type(items[key]) == dict:
size = items[key].get('size')
if size is not None and items[key].get('size') > biggest:
biggest = size
name = key
print name
you can also use list comprehension:
val=max([x["size"] for x in [a,b,c]])
Related
I'm trying to create a multiple hierarchy of nested dictionary. The hierarchy levels are separated with a dot(.) in variable B however the final key (A) and value (D) are fixed.
Variables
A = "key"
B = "one.two.three.four"
D = "value"
Desired Output
{ one : { two : {three : {four : {key: value}}}}}
Here, the length of hierarchy (variable B) might increase or decrease based on input. I'm unable to create such dynamic code.
My pseudocode Code
A = "key"
B = "one.two.three.four"
D = "value"
inner_dictionary = {}
whole_dictionary = {}
lst = B.split('.')
length = len(lst)
for i in range(length):
new = lst[-1]
tmp = {A:D}
inner_dictionary.update(tmp)
val = { new : inner_dictionary}
whole_dictionary.update(val)
lst.pop()
print(whole_dictionary)
My Output
{'four': {'key': 'value'}, 'three': {'key': 'value'}, 'two': {'key': 'value'}, 'one': {'key': 'value'}}
I need help on this. Thanks in advance!
Use this:
A = "key"
B = "one.two.three.four"
D = "value"
x = {A: D}
for k in B.split('.')[::-1]:
x = {k: x}
print(x)
Output:
{'one': {'two': {'three': {'four': {'key': 'value'}}}}}
Or, in Python 3.8+, using the walrus operator:
A = "key"
B = "one.two.three.four"
D = "value"
x = {A: D}
[(x := {k: x}) for k in B.split('.')[::-1]]
print(x)
Output:
{'one': {'two': {'three': {'four': {'key': 'value'}}}}}
Note: the second solution takes a lot more time (you can run the following code to check that):
from timeit import timeit
print(timeit("""A = "key"
B = "one.two.three.four"
D = "value"
x = {A: D}
for k in B.split('.')[::-1]:
x = {k: x}"""))
print(timeit("""A = "key"
B = "one.two.three.four"
D = "value"
x = {A: D}
[(x := {k: x}) for k in B.split('.')[::-1]]"""))
The first one takes about 0.5s, the second one about 1s.
One approach using a single for-loop:
A = "key"
B = "one.two.three.four"
D = "value"
start = { A: D }
for k in reversed(B.split(".")):
start = { k : start }
print(start)
Output
{'one': {'two': {'three': {'four': {'key': 'value'}}}}}
This type of problem where a list of values aggregates to a single one can be solved using reduce (a la functional programming):
from functools import reduce
A = "key"
B = "one.two.three.four"
D = "value"
res = reduce(lambda x, y: {y: x}, reversed(B.split(".")), {A: D})
I have a dict in python with key values and for values I have one variable included in it . I want to change the value of variable at run time. How to do that as it initializes the dict at inital.
Suppose it is as:
number = ""
dict = { "a": ["welcome" + number + " Back"] } # number = ""
Now if I do as number = 45 somehow calculated. I want to auto-update the dict to as :
dict={ "a" :["welcome" + number + " Back"] } # number = 45
But dict is updated at initial stage and it is not changing value of number at run time.
ints are immutable in Python, but you could do a similar thing with a mutable structure, like a list:
>>> number = [""]
>>> d={"a":["welcome Back", number]}
>>> d
{'a': ['welcome Back', ['']]}
>>> number[0] = 45
>>> d
{'a': ['welcome Back', [45]]}
In this case the dict contains a reference to the mutable list, so the dict is updated when the list changes.
Instead of self-referencing dictionary values I'd recommend you just use classes instead.
Anyway, here's a possible way to achieve what you want:
dct = {
"a": lambda: ["welcome {} back".format(dct["number"])],
"number": ""
}
for number in ["one", "two", "three"]:
dct["number"] = number
print(dct["a"]())
you can use list of list
>>> n = ['']
>>> d = {'a': ["welcome", n, "back"]}
>>> d
{'a': ['welcome', [''], 'back']}
>>> n[0] = 45
>>> d
{'a': ['welcome', [45], 'back']}
I have two lists seen here.
a = ['a','b','a']
b = [200,300,300]
when I print like so:
print dict(zip(a,b))
I get:
{'A': 300, 'B': 300}
How would I aggregate the values based off the keys so that I get
{'A': 500, 'B': 300} ?
result = {}
for k,v in zip (['a','b','a'], [200,300,300]):
result[k] = result.get(k,0) + v
print result
from collections import Counter
a = ['a','b','a']
b = [200,300,300]
c = Counter()
for i, j in zip(a, b):
c[i] += j
print(c)
I suppose a clear way (per Python's Zen) to achieve your goal is:
from __future__ import print_function
a = ['a','b','a']
b = [200,300,300]
d = dict()
for place, key in enumerate(a):
try:
d[key] += b[place]
except KeyError:
d[key] = b[place]
print(d)
Which gives your expected output:
{'a': 500, 'b': 300}
You just need to iterate over zip for key and values and put them in dictionary.
a = ['a','b','a']
b = [200,300,300]
for key, val in zip(a,b):
if key in combined_dict:
combined_dict[key] += val
else:
combined_dict[key] = val
print(combined_dict)
=> {'a': 500, 'b': 300}
One way to do it is like below, by avoiding zip function,
aggregateDict = {}
a= ['a', 'b', 'a']
b=[200, 300, 200]
for i in range(len(a)):
aggregateDict[a[i]] = aggregateDict.get(a[i], 0) + b[i]
Output will be
{'a': 400, 'b': 300}
I'd appreciate help for this apparently simple task: write a function that will take a tuple and return a nested dictionary, with each successive value in the tuple being a key in a successively deeper 'layer' of the dictionary.
The ultimate 'value' at the bottom of the rainbow is specified (say 10, in the following example).
So from the tuple ('cat', 'dog', 'bone'), I'm aiming to have as an output:
{'cat':{'dog':{'bone':10}}}
and to do this for tuples of arbitrary length.
How is that 'ultimate value' specified exactly?
In the code below it is specified by named argument:
def nested_dict(tuple, value=10):
if len(tuple) is 1:
return { tuple[0] : value }
return { tuple[0] : nested_dict(tuple[1:], value=value) }
t = ('cat','dog','bone')
answer = {}
temp = answer
for key in t[:-1]:
if key not in temp:
temp[key] = {}
temp = temp[key]
temp[t[-1]] = 10
Output:
In [21]: answer
Out[21]: {'cat': {'dog': {'bone': 10}}}
My attempt as well:
>>> t = ('cat', 'dog', 'bone')
>>> last = {t[-1]: 10}
>>> for e in t[1::-1]:
... last = {e: last}
...
>>> last
{'cat': {'dog': {'bone': 10}}}
I'm not even able to properly search google for it, but here goes:
a = {}
b = {}
c = [a, b]
for d in c:
d['ID'] = d
print c
returns:
[{'ID': {...}}, {'ID': {...}}]
why isn't it:
[{'ID': a}, {'ID': b}]
Let's step through this:
a = {}
b = {}
c = [a, b]
So far, so good.
for d in c:
d['ID'] = d
We can unroll this to:
d = c[0]
d['ID'] = d
d = c[1]
d['ID'] = 1
And expand that to:
d = a
d['ID'] = d
d = b
d['ID'] = d
Now substitute:
a['ID'] = a
b['ID'] = a
So, let's forget about the loop for a second and look at what that does:
>>> a = {}
>>> a['ID'] = a
>>> a
{'ID': {...}}
In other words, you're making each dict recursively contain a copy of itself, under the key ID. How would you expect this to be printed?
So, the obvious thing to do is to try to print the whole dictionary:
{'ID': {'ID': {'ID': { …
But this would be an infinitely-long string, and Python would run out of stack space before reaching infinity. So it needs to truncate it somehow.
It can't print this:
{'ID': a}
Because a is just a name that happens to be bound to the dict, just like d is at the time. In fact, the loop doesn't even know that a is bound to that at the time; it knows that d is. But even if it did know, the result would be wrong. Think about this:
>>> e = a
>>> a = 0
>>> e
???
So, the obvious answer is to use an ellipsis (kind of like I did in the human-readable version) to represent "and so on".
a is a dictionary.
b is a dictionary.
c is a list of two dictionaries (not "two names" or "two variables").
Another socratic explanation:
If it would return [{'ID': a}, {'ID': b}], values displayed as a and b would be of which type?
Consider what the loop is doing:
a = {}
b = {}
c = [a, b]
for d in c:
d['ID'] = d
d will be either a or b, such that
a['ID'] = a
b['ID'] = b
but recall a and b are {}, the dics themselves. as a result, your assigning ['ID'] to the dic itself, creating a loop. When you
print(c)
you get [{'ID': {...}}, {'ID': {...}}] because the value of the key is the dic itself and not the variable representation of it, hence you get {...} to reflect the nature of the loop.
Note how after this a['ID']['ID'], or even a ['ID']['ID']['ID']['ID'] is {'ID': {...}}, because the value of the key is the dic itself, not the variable pointing to it.
for d in c:
d['ID'] = d
should be
c = [{'ID': d} for d in c]
Your code is adding the ID element to each of the dicts in c. That means a = {'ID': a} after your code has run. It contains a reference to itself.
My snippet generates a new dict with a property 'ID' containing a value from c.