Python 3: for loop syntax with dictionary

The following code snippet works:

param = {}

for nround_counter in [1,2,3]:
    { 
        print(nround_counter)
        #param = {'objective' : 'multi:softmax'}

    } 

But the following doesn't:

param = {}

for nround_counter in [1,2,3]:
    { 
        print(nround_counter)
        param = {'objective' : 'multi:softmax'}

    } 

The error given is invalid syntax. I am new to Python, and seek help in debugging the above.

Thank you.


Asked by: Lily717 | Posted: 27-01-2022






Answer 1

Bodies of code such as loops, functions, classes, etc. are not enclosed by braces in Python. Indentation is what determines code structure.

for nround_counter in [1, 2, 3]:
    print(nround_counter)
    param = {'object' : 'multi:softmax'}

Answered by: Daryl731 | Posted: 28-02-2022



Answer 2

You're conflating much different issues here.

Here's your first example, rendered with whitespace more conventionally used for Python:

#!python3
param = {}

for nround_counter in [1,2,3]:
    { print(nround_counter) }

Note that this is iterating over a series of statements, the statement is (uselessly and confusingly) being coded into a set literal constructor expression, being called for its side effect (calling the print function). It's not modifying any state, but it's evaluated as a set, containing the None singleton as its only element, on each iteration through the loop.

This is not a special syntax. It's just an incomprehensible usage of Python's set literal construction syntax.

It's also completely unclear what you're trying to accomplish. It make no sense to loop over a list continually binding param to the same literal dictionary contents over and over.

Perhaps if you wanted to build some sort of table?

param = dict()
for n in range(1,4):
    print(n)
    param['objective%s'%n] = 'multi:softmax'

... or something like that. Note I initialize param with dict() rather than the literal {} because I think it's a bit cleaner and more clear, if slightly more verbose. Also I'm using range(1,4) rather than your literal list, again because it's cleaner. What I'm doing in the body of this loop is silly, but it's an example of what you could do.

Note that I'm generating a unique key (a constant string literal with interpolation of the string representation of my iterator variable) for each pass through the loop. One would normally expect the values to also be dynamically computed or derived in some way; but I don't how that as there's no clear pedagogical example that comes to mind.

Answered by: Grace519 | Posted: 28-02-2022



Similar questions

C# way to mimic Python Dictionary Syntax

Is there a good way in C# to mimic the following python syntax: mydict = {} mydict["bc"] = {} mydict["bc"]["de"] = "123"; # <-- This line mydict["te"] = "5"; # <-- While also allowing this line In other words, I'd like something with [] style access that can return either another dictionary or a string type, depending on how it has been set. I've been trying to work...


python - Syntax - saving a dictionary as a csv file

I am trying to "clean up" some data - I'm creating a dictionary of the channels that I need to keep and then I've got an if block to create a second dictionary with the correct rounding. Dictionary looks like this: {'time, s': (imported array), 'x temp, C':(imported array), 'x pressure, kPa': (diff. imported array).....etc} Each imported array is 1-d. I was ...


Python Syntax Error with Dictionary

I am trying to do the following code: while y < x: data_list[y].title = title data_list[y].link = link data_list[y].description = description story_list.update({title: link, description}) y += 1 Where x is len(data_list) and y = 0 outside the loop. When I try to run it, I get a syntax error for '}' only (not on the '{' bracket though) on the dict...


Python Dictionary Syntax Error [learn python the hard way -ex39]

states = [ 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' ] print states.Oregon Why is this code showing syntax error in line 2? Running on python 2.7.12 (default on ubuntu)


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python, dictionary and int error

I have a very frustrating python problem. In this code fixedKeyStringInAVar = "SomeKey" def myFunc(a, b): global sleepTime global fixedKeyStringInAVar varMe=int("15") sleepTime[fixedKeyStringInAVar] = varMe*60*1000 #more code Now this works. BUT sometimes when I run this function I get TypeError: 'int' object does not support item assignment


python - Best way to create a NumPy array from a dictionary?

I'm just starting with NumPy so I may be missing some core concepts... What's the best way to create a NumPy array from a dictionary whose values are lists? Something like this: d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } Should turn into something like: data = [ [10,20,30,?,?], [50,60,?,?,?], [100,200,300,400,500] ] ...


python - List a dictionary

In a list appending is possible. But how I achieve appending in dictionary? Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | OBJECT|00000101| |.rodata Symbols from _ashldi3.o: Name Value Class ...


python - How to filter a dictionary by value?

Newbie question here, so please bear with me. Let's say I have a dictionary looking like this: a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} I want all values that are equal to each other to be moved into...


Python and dictionary like object

I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary). But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using isinstance and type (because they are considered b...


python - Remove dictionary from list

If I have a list of dictionaries, say: [{'id': 1, 'name': 'paul'}, {'id': 2, 'name': 'john'}] and I would like to remove the dictionary with id of 2 (or name 'john'), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).


C# way to mimic Python Dictionary Syntax

Is there a good way in C# to mimic the following python syntax: mydict = {} mydict["bc"] = {} mydict["bc"]["de"] = "123"; # &lt;-- This line mydict["te"] = "5"; # &lt;-- While also allowing this line In other words, I'd like something with [] style access that can return either another dictionary or a string type, depending on how it has been set. I've been trying to work...


python - Can a dictionary be passed to django models on create?

Is it possible to do something similar to this with a list, dictionary or something else? data_dict = { 'title' : 'awesome title', 'body' : 'great body of text', } Model.objects.create(data_dict) Even better if I can extend it: Model.objects.create(data_dict, extra='hello', extra2='world')


python - Make Dictionary From 2 List

This question already has answers here:


sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}


Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: &gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.


python - How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?


python - How can I make a dictionary from separate lists of keys and values?

I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}


python - Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom)


Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?


python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...


python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python - Check if a given key already exists in a dictionary and increment it

How do I find out if a key in a dictionary has already been set to a non-None value? I want to increment the value if there's already one there, or set it to 1 otherwise: my_dict = {} if my_dict[key] is not None: my_dict[key] = 1 else: my_dict[key] += 1






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top