Suppose I have the following dict:
L = {'A': {'root[1]': 'firstvalue', 'root[2]': 'secondvalue'}, 'B': {'root[3]': 'thirdvalue', 'root[4]': 'Fourthvalue'}}
How can I access the values of the keys root[1], root[2], root[3], root[4] (indexes of root[] is dynamic) in Python 2.7.
Try :
>>> L = {'A': {'root[1]': 'firstvalue', 'root[2]': 'secondvalue'}, 'B': {'root[3]': 'thirdvalue', 'root[4]': 'Fourthvalue'}}
>>> L['A']['root[1]']
'firstvalue'
>>> L['A']['root[2]']
'secondvalue'
>>> L['B']['root[3]']
'thirdvalue'
>>> L['B']['root[4]']
'Fourthvalue'
>>>
Something like this:
for (key, value) in L.items():
for (another_key, real_value) in value.items():
print(another_key, real_value)
To access the values from a dict nested inside the dict, i used the following step:
L = {'A': {'root[1]': 'firstvalue', 'root[2]': 'secondvalue'}, 'B': {'root[3]': 'thirdvalue', 'root[4]': 'Fourthvalue'}}
Solution:
F = {}
G = []
F = L.get("A", None)
F= {{'root[1]': 'firstvalue', 'root[2]': 'secondvalue'}}
for value in F.values():
G.append(value)
Output:
G = ['firstvalue', 'secondvalue']
Related
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 6 dict like this
dict1
dict2
dict3
dict4
dict5
dict6
now I want all of this in one dict. so I used this
dict1.update({'dict2':dict2})
dict3.update({'dict1':dict1})
dict4.update({'dict4':dict3})
dict5.update({'dict5':dict4})
dict6.update({'dict6':dict5})
at last dict6 contains all value but it's not formatted correctly and it's not the pythonic way to do it
I want to improve this any suggestions
right now I'm getting like this but I don't want like this
{"main_responses": {"dict1": {"dict2": {"dict3": {"dict4": {"dict5": {}}}}}}}
i want
{"main_responses":{ "dict1": {dict1_values}, "dict2": {dict2_values}..... and so on
Try this:
from itertools import chain
d = chain.from_iterable(d.items() for d in (ada_dict,
wordpress_version_dict,
drupal_version_dict,
ssl_dict,
link_dict,
tag_dict))
api_response = {'api_response':d}
Or this, using reduce:
d = reduce(lambda x,y: dict(x, **y), (ada_dict,
wordpress_version_dict,
drupal_version_dict,
ssl_dict,
link_dict,
tag_dict))
api_response = {'api_response':d}
Giving a very similar example of my own based on your requirements:
>>> d1 = {'a':1}
>>> d2 = {'b':2}
>>> d3 = {'c':3}
>>> d4 = {'d':4}
#magic happens here
>>> d = {'d1':d1 , 'd2':d2, 'd3':d3, 'd4':d4}
>>> d
=> {'d1': {'a': 1}, 'd2': {'b': 2}, 'd3': {'c': 3}, 'd4': {'d': 4}}
Since you do not have all the dictionaries that you want added in one place, this is about as easy as it gets.
In case you want to add another key to your collection of all dictionaries (d here), do:
>>> out = {'api_responses': d}
#or in one step if you do not want to use `d`
>>> out = {'api_responses': {'d1':d1 , 'd2':d2, 'd3':d3, 'd4':d4}}
>>> out
=> {'api_responses': {'d1': {'a': 1}, 'd2': {'b': 2}, 'd3': {'c': 3}, 'd4': {'d': 4}}}
If you want add all dict in a single one "newDict", Be carrefull if several keys exist in multiple Dict :
ada_dict={'k1':'v1'}
wordpress_version_dict={'k2':'v2'}
drupal_version_dict={'k3':'v3'}
ssl_dict={'k4':'v4'}
link_dict={'k5':'v5'}
tag_dict={'k5':'v5'}
newDict={}
newDict.update( (k,v) for k,v in ada_dict.iteritems() if v is not None)
newDict.update( (k,v) for k,v in wordpress_version_dict.iteritems() if v is not None)
newDict.update( (k,v) for k,v in drupal_version_dict.iteritems() if v is not None)
newDict.update( (k,v) for k,v in ssl_dict.iteritems() if v is not None)
newDict.update( (k,v) for k,v in link_dict.iteritems() if v is not None)
newDict.update( (k,v) for k,v in tag_dict.iteritems() if v is not None)
print {'api_response':newDict}
https://repl.it/ND3p/1
please add more comment to your post, but as I see you need something like , is not it ?
>>> foo=lambda dest, src, tag: [dest.update({tag:i}) for i in src]
>>> x={1:1}
>>> y={2:2}
>>> foo(x, y, "tag")
[None]
>>> x
{1: 1, 'tag': 2}
>>> y
{2: 2}
Does this help in getting the output you want?
new_dict=dict(ada_dict.items()+wordpress_version_dict.items() +drupal_version_dict.items()+ssl_dict.items()+link_dict.items()+tag_dict.items())
a =[ada_dict,
wordpress_version_dict,
drupal_version_dict,
ssl_dict,
link_dict,
tag_dict]
c= {}
for i in a:
c.update({i:i})
print c
{'ada_dict': 'ada_dict',
'drupal_version_dict': 'drupal_version_dict',
'link_dict': 'link_dict',
'ssl_dict': 'ssl_dict',
'tag_dict': 'tag_dict',
'wordpress_version_dic': 'wordpress_version_dic'}
d={}
d.update({"api_responses":c})
print d
{'api_responses': {'ada_dict': 'ada_dict',
'drupal_version_dict': 'drupal_version_dict',
'link_dict': 'link_dict',
'ssl_dict': 'ssl_dict',
'tag_dict': 'tag_dict',
'wordpress_version_dic': 'wordpress_version_dic'}}
I want to create a nested dict in python dynamically. By saying that:
given
tuple1 = ('A','B'),
tuple2 = ('A','C'),
dict = {}
I'd like to have dict like dict = {'A': {'B':1}} after adding tuple1 to dict;
then dict = {'A': {'B' : 1, 'C' : 1}} after adding tuple2 to dict
That's what I have tried, i find the following code to create nested dict recursively. But I'm not sure how to add node dynamically and also increment its value by 1.
def incr_dict(dct, tpl):
if len(tpl) == 0:
dct = dct
else:
dct = {tpl[-1]:dct}
return incr_dict(dct, tpl[0:-1])
return dct
dct = {}
tpl = ('a', 'b', 'c')
dct = incr_dict(dct, tpl)
print(dct)
At the end of the below code, you will have a dict d which is {'A': {'B': 1, 'C': 1}}; note that the outermost loop isn't strictly necessary, but it saved me some typing in this instance.
tuple1 = ('A','B')
tuple2 = ('A','C')
d = {}
for l in [list(tuple1), list(tuple2)]:
for k in l:
v = l.pop()
if (d.has_key(k)):
if (d[k].has_key(v)):
d[k][v] = d[k][v]+1
else:
d[k][v] = 1
else:
d[k] = {}
d[k][v] = 1
I am using Python 3.3. I was curious how I can make a dictionary out of a list:
Lets say my list containing strings is
list = ['a;alex', 'a;allison', 'b;beta', 'b;barney', 'd;doda', 'd;dolly']
I want to make it into a dictionary like this:
new_dict = { {'a': {'alex','allison'}}
{'b': {'beta','barney'}}
{'d': {'doda', 'dolly'}} }
so later I can print it out like this:
Names to be organized and printed:
a -> {'alex', 'allison'}
b -> {'beta', 'barney'}
d -> {'doda', 'dolly'}
How would I approach this? Many thanks in advance!
-UPDATE-
So far I have this:
reached_nodes = {}
for i in list:
index = list.index(i)
reached_nodes.update({list[index][0]: list[index]})
But it outputs into the console as:
{'a': 'a;allison', 'b': 'b;barney', 'd': 'd;dolly'}
Well, you can use defaultdict:
>>> from collections import defaultdict
>>> l = ['a;alex', 'a;allison', 'b;beta', 'b;barney', 'd;doda', 'd;dolly']
>>> var = defaultdict(list)
>>> for it in l:
a, b = it.split(';')
var[a].append(b)
>>> var
defaultdict(<type 'list'>, {'a': ['alex', 'allison'], 'b': ['beta', 'barney'], 'd': ['doda', 'dolly']})
>>> for key, item in var.items():
... print "{} -> {{{}}}".format(key, item)
...
a -> {['alex', 'allison']}
b -> {['beta', 'barney']}
d -> {['doda', 'dolly']}
If you would like to get rid of the [], then try the following:
>>> for key, value in var.items():
... print "{} -> {{{}}}".format(key, ", ".join(value))
a -> {alex, allison}
b -> {beta, barney}
d -> {doda, dolly}
If you would like the values in a set and not a list, then just do the following:
var = defaultdict(set)
And use .add instead of .append.
how join list tuple and dict into a dict?
['f','b','c','d'] (1,2,3) and {'a':'10'}
d excluded for list be compatible with the tuple
output {'f':'1','b':'2','c':'3','a':'10'}
You can make a dict from keys and values like so:
keys = ['a','b','c','d']
values = (1,2,3)
result = dict(zip(keys, values)) # {'a': 1, 'c': 3, 'b': 2}
Then you can update it with another dict
result.update({ 'f' : 5 })
print result # {'a': 1, 'c': 3, 'b': 2, 'f': 5}
dict(zip(a_list, a_tuple)).update(a_dictionary)
when a_list is your list, a_tuple is your tuple and a_dictionary is your dictionary.
EDIT:
If you really wanted to turn the numbers in you tuple into strings than first do:
new_tuple = tuple((str(i) for i in a_tuple))
and pass new_tuple to the zip function.
This will accomplish the first part of your question:
dict(zip(['a','b','c','d'], (1,2,3)))
However, the second part of your question would require a second definition of 'a', which the dictionary type does not allow. However, you can always set additional keys manually:
>>> d = {}
>>> d['e'] = 10
>>> d
{'e':10}
The keys in a dictionary must be unique, so this part: {'a':'1','a':'10'} is impossible.
Here is code for the rest:
l = ['a','b','c','d']
t = (1,2,3)
d = {}
for key, value in zip(l, t):
d[key] = value
Something like this?
>>> dict({'a':'10'}.items() + (zip(['f','b','c','d'],('1','2','3'))))
{'a': '10', 'c': '3', 'b': '2', 'f': '1'}
Since noone has given an answer that converts the tuple items to str yet
>>> L=['f','b','c','d']
>>> T=(1,2,3)
>>> D={'a':'10'}
>>> dict(zip(L,map(str,T)),**D)
{'a': '10', 'c': '3', 'b': '2', 'f': '1'}
>>> l = ['a','b','c','d']
>>> t = (1,2,3)
>>> d = {'a':'10'}
>>> t = map(str, t) # the OP has requested str values, let's do this first
If you are OK with mutating the original dict, then you can just do this:
>>> d.update(zip(l, t))
or in Python 3.9+ (PEP 584):
>>> d |= zip(l, t)
But if you need to keep the original d intact:
>>> new_d = dict(zip(l, t))
>>> new_d |= d