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










1















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)









share|improve this question
























  • Please post your JSON data, its very hard to visualize

    – Kunal Mukherjee
    Mar 21 at 18:15















1















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)









share|improve this question
























  • Please post your JSON data, its very hard to visualize

    – Kunal Mukherjee
    Mar 21 at 18:15













1












1








1


1






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)









share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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

















  • 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












1 Answer
1






active

oldest

votes


















2














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.






share|improve this answer























  • 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











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
);



);













draft saved

draft discarded


















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









2














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.






share|improve this answer























  • 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















2














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.






share|improve this answer























  • 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













2












2








2







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.






share|improve this answer













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.







share|improve this answer












share|improve this answer



share|improve this answer










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

















  • 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



















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript