Build a nested dictionary with a list The Next CEO of Stack OverflowHow to merge two dictionaries in a single expression?How do I check if a list is empty?How do I sort a list of dictionaries by a value of the dictionary?How can I safely create a nested directory in Python?How do I sort a dictionary by value?How to make a flat list out of list of lists?Add new keys to a dictionary?Check if a given key already exists in a dictionaryHow do I list all files of a directory?Iterating over dictionaries using 'for' loops
Yu-Gi-Oh cards in Python 3
Proper way to express "He disappeared them"
How to write a definition with variants?
TikZ: How to reverse arrow direction without switching start/end point?
Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?
If the heap is zero-initialized for security, then why is the stack merely uninitialized?
When you upcast Blindness/Deafness, do all targets suffer the same effect?
How did people program for Consoles with multiple CPUs?
Where do students learn to solve polynomial equations these days?
Is the D&D universe the same as the Forgotten Realms universe?
Why do airplanes bank sharply to the right after air-to-air refueling?
Can Plant Growth be repeatedly cast on the same area to exponentially increase the yield of harvests there (more than twice)?
Flying from Cape Town to England and return to another province
Is it okay to majorly distort historical facts while writing a fiction story?
What flight has the highest ratio of timezone difference to flight time?
Method for adding error messages to a dictionary given a key
Do they change the text of the seder in Israel?
How I can get glyphs from a fraktur font and use them as identifiers?
Unclear about dynamic binding
Easy to read palindrome checker
Axiom Schema vs Axiom
Why, when going from special to general relativity, do we just replace partial derivatives with covariant derivatives?
Why don't programming languages automatically manage the synchronous/asynchronous problem?
Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?
Build a nested dictionary with a list
The Next CEO of Stack OverflowHow to merge two dictionaries in a single expression?How do I check if a list is empty?How do I sort a list of dictionaries by a value of the dictionary?How can I safely create a nested directory in Python?How do I sort a dictionary by value?How to make a flat list out of list of lists?Add new keys to a dictionary?Check if a given key already exists in a dictionaryHow do I list all files of a directory?Iterating over dictionaries using 'for' loops
I am struggling with how to define a list and append to it while looping through parsed json doc. I can't append to the list that's not defined. But I don't want to set to empty list, as that would override values I had in it in next iteration. This is what I have:
from collections import defaultdict
nested_dict = lambda: defaultdict(nested_dict)
hash = nested_dict()
for e in decoded_jason['volumeList']:
volumeName = e['name']
volumeType = e['volumeType']
if volumeType == 'Snapshot':
consistencyGroupId = e['consistencyGroupId']
#I am missing a step here to initialize empty list so I can append
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
if I do this before append, it works, but then the list will be set to empty in next iteration:
hash['map']['consistencyGroup'][consistencyGroupId]=[]
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
python
add a comment |
I am struggling with how to define a list and append to it while looping through parsed json doc. I can't append to the list that's not defined. But I don't want to set to empty list, as that would override values I had in it in next iteration. This is what I have:
from collections import defaultdict
nested_dict = lambda: defaultdict(nested_dict)
hash = nested_dict()
for e in decoded_jason['volumeList']:
volumeName = e['name']
volumeType = e['volumeType']
if volumeType == 'Snapshot':
consistencyGroupId = e['consistencyGroupId']
#I am missing a step here to initialize empty list so I can append
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
if I do this before append, it works, but then the list will be set to empty in next iteration:
hash['map']['consistencyGroup'][consistencyGroupId]=[]
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
python
Please post your JSON data, its very hard to visualize
– Kunal Mukherjee
Mar 21 at 18:15
add a comment |
I am struggling with how to define a list and append to it while looping through parsed json doc. I can't append to the list that's not defined. But I don't want to set to empty list, as that would override values I had in it in next iteration. This is what I have:
from collections import defaultdict
nested_dict = lambda: defaultdict(nested_dict)
hash = nested_dict()
for e in decoded_jason['volumeList']:
volumeName = e['name']
volumeType = e['volumeType']
if volumeType == 'Snapshot':
consistencyGroupId = e['consistencyGroupId']
#I am missing a step here to initialize empty list so I can append
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
if I do this before append, it works, but then the list will be set to empty in next iteration:
hash['map']['consistencyGroup'][consistencyGroupId]=[]
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
python
I am struggling with how to define a list and append to it while looping through parsed json doc. I can't append to the list that's not defined. But I don't want to set to empty list, as that would override values I had in it in next iteration. This is what I have:
from collections import defaultdict
nested_dict = lambda: defaultdict(nested_dict)
hash = nested_dict()
for e in decoded_jason['volumeList']:
volumeName = e['name']
volumeType = e['volumeType']
if volumeType == 'Snapshot':
consistencyGroupId = e['consistencyGroupId']
#I am missing a step here to initialize empty list so I can append
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
if I do this before append, it works, but then the list will be set to empty in next iteration:
hash['map']['consistencyGroup'][consistencyGroupId]=[]
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
python
python
edited Mar 21 at 18:23
petezurich
3,76581936
3,76581936
asked Mar 21 at 18:12
MarjanaMarjana
61
61
Please post your JSON data, its very hard to visualize
– Kunal Mukherjee
Mar 21 at 18:15
add a comment |
Please post your JSON data, its very hard to visualize
– Kunal Mukherjee
Mar 21 at 18:15
Please post your JSON data, its very hard to visualize
– Kunal Mukherjee
Mar 21 at 18:15
Please post your JSON data, its very hard to visualize
– Kunal Mukherjee
Mar 21 at 18:15
add a comment |
1 Answer
1
active
oldest
votes
Make your final line be:
hash['map']['consistencyGroup'].setdefault(consistencyGroupId, []).append(volumeName)
setdefault
either returns the value for the key if it's present, or, if it's not, sets it to the provided default ([]
in this case), and then returns that.
Thank you Donnie, that works! I was trying with setdefault but I wasn't using it correctly (instead of consistencyGroupId, I had the whole hash thing.
– Marjana
Mar 21 at 18:27
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55286774%2fbuild-a-nested-dictionary-with-a-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Make your final line be:
hash['map']['consistencyGroup'].setdefault(consistencyGroupId, []).append(volumeName)
setdefault
either returns the value for the key if it's present, or, if it's not, sets it to the provided default ([]
in this case), and then returns that.
Thank you Donnie, that works! I was trying with setdefault but I wasn't using it correctly (instead of consistencyGroupId, I had the whole hash thing.
– Marjana
Mar 21 at 18:27
add a comment |
Make your final line be:
hash['map']['consistencyGroup'].setdefault(consistencyGroupId, []).append(volumeName)
setdefault
either returns the value for the key if it's present, or, if it's not, sets it to the provided default ([]
in this case), and then returns that.
Thank you Donnie, that works! I was trying with setdefault but I wasn't using it correctly (instead of consistencyGroupId, I had the whole hash thing.
– Marjana
Mar 21 at 18:27
add a comment |
Make your final line be:
hash['map']['consistencyGroup'].setdefault(consistencyGroupId, []).append(volumeName)
setdefault
either returns the value for the key if it's present, or, if it's not, sets it to the provided default ([]
in this case), and then returns that.
Make your final line be:
hash['map']['consistencyGroup'].setdefault(consistencyGroupId, []).append(volumeName)
setdefault
either returns the value for the key if it's present, or, if it's not, sets it to the provided default ([]
in this case), and then returns that.
answered Mar 21 at 18:17
DonnieDonnie
35.4k75478
35.4k75478
Thank you Donnie, that works! I was trying with setdefault but I wasn't using it correctly (instead of consistencyGroupId, I had the whole hash thing.
– Marjana
Mar 21 at 18:27
add a comment |
Thank you Donnie, that works! I was trying with setdefault but I wasn't using it correctly (instead of consistencyGroupId, I had the whole hash thing.
– Marjana
Mar 21 at 18:27
Thank you Donnie, that works! I was trying with setdefault but I wasn't using it correctly (instead of consistencyGroupId, I had the whole hash thing.
– Marjana
Mar 21 at 18:27
Thank you Donnie, that works! I was trying with setdefault but I wasn't using it correctly (instead of consistencyGroupId, I had the whole hash thing.
– Marjana
Mar 21 at 18:27
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55286774%2fbuild-a-nested-dictionary-with-a-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Please post your JSON data, its very hard to visualize
– Kunal Mukherjee
Mar 21 at 18:15