Ошибка expression cannot contain assignment perhaps you meant

I am creating a dictionary object, it gets created while I use «Statement 1», however I get an error message while try create a dictionary object using same keys and values with «Statement 2».

Statement 1:

dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 
        4: 'Fri', 5: 'Sat', 6: 'Sun'}

Statement 2:

dmap = dict(0='Mon', 1='Tue', 2='Wed', 3='Thu', 
            4='Fri', 5='Sat', 6='Sun'

Error message:

    File "<stdin>", line 1
    SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

Can someone tell me, why am I allowed to create dictionary with integer keys using Statement 1, but not with Statement 2?

Edited
Using an updated version of Statement 2, I am able to create dictionary object with below code:

dmap = dict(day_0='Mon', day_1='Tue', day_2='Wed', 
            day_3='Thu', day_4='Fri', day_5='Sat', day_6='Sun')

Нерабочий кусок кода:

SETTINGS_FILE = open('settings.py', '+a')

def check_settings():
    for i in SETTINGS:
        if i == 'font_face':
            SETTINGS_FILE.write(SETTINGS['font_face'] = 'JetBrains Mono')
            SETTINGS_FILE.close()
            print(i)

Ошибка:

File "F:ПУТЬ_К_ПРОЕКТУПРОЕКТmain.py", line 24
    SETTINGS_FILE.write(SETTINGS['font_face'] = 'JetBrains Mono')
                        ^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?


  • Вопрос задан

    более года назад

  • 1111 просмотров

Пригласить эксперта

Ваще не понимаю в чем вопрос, интерпретатор абсолютно точно указал где ошибка и в чем она заключается. Почему бы просто не перевести то, что написано и подумать головой?

Мисье, я все понимаю, но интерпритатор все вам четко разьяснил.
Не соизволите ли вы поставить == в 7 строчке?

SETTINGS_FILE.write(SETTINGS[‘font_face’] == ‘JetBrains Mono’)

Авось и заработает?


  • Показать ещё
    Загружается…

13 июн. 2023, в 15:10

25000 руб./за проект

13 июн. 2023, в 14:58

40000 руб./за проект

13 июн. 2023, в 14:45

3500 руб./за проект

Минуточку внимания

#python #list #lambda

#python #Список #лямбда

Вопрос:

У меня есть список:

 goods = [True, False, True, True, False, True, False]
 

Мне нужно инвертировать некоторые значения по индексам, например: 1, 3, 4
Это означает, что goods[1] будет True, goods [3] — False, goods [4] — True .
Если я делаю это в map lambda, я улавливаю ошибку, подобную этой:

 SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

list(map(lambda x: goods[x]=True if goods[x] is False else True, [1, 3, 4]))
 

Почему я не могу изменить значение списка в таком случае?

Комментарии:

1. Условное выражение (X, если Y, иначе Z) требует выражений для каждого компонента. goods[x]=True это не выражение; это оператор присваивания. Если вы пытаетесь изменить содержимое goods in place , помещение присваивания внутрь map не является жизнеспособным способом сделать это.

2. Вы могли бы просто написать прямой цикл for.

Ответ №1:

Не пытайтесь злоупотреблять пониманием (или коллекциями) из-за побочных эффектов. Почему бы просто не:

 for x in [1, 3, 4]:
    goods[x] = not goods[x]
 

Если бы из-за какого-то ошибочного эстетического чувства кто-то отчаянно хотел использовать лямбда-функцию, вам пришлось бы использовать ее для перестройки самих goods себя (лямбды могут содержать только одно выражение, а не оператор, где присваивание является оператором):

 goods[:] = map(lambda x: not x[1] if x[0] in [1, 3, 4] else x[1], enumerate(goods))
 

Хотя в этом нет ничего изящного =)

Комментарии:

1. Это более простой и правильный способ сделать это. 1

2. И если это должно быть однострочное, просто сделайте for x in [1, 3, 4]: goods[x] = not goods[x] xD

3. Согласитесь, это более простой и легкий способ сделать это. Но есть ли способ сделать это с помощью лямбды и т.д.? Я хотел бы сделать это более изящно, если это возможно. Как вы думаете? Строка, подобная этой для x в [1, 3, 4]: товары [x] = не товары [x] выглядят хорошо, но не целиком в PIP8

4. Я добавил опцию. Однако, почему кто-то связывает лямбды и грацию, мне не понять 😉

5. Да, выглядит не очень просто) Левый первый вариант)

Ответ №2:

Если numpy является опцией, возможно, что-то вроде этого:

 import numpy as np

goods = np.array([True, False, True, True, False, True, False])
goods[[1,3,4]] ^= True     # xor to flip booleans
print(goods)   # [True  True   True  False True   True  False]
 

In Python, there are three main types of errors: Syntax errors, Runtime errors, and Logical errors. Syntax errors can include system errors and name errors. System errors occur when the interpreter encounters extraneous tabs and spaces, given that proper indentation is essential for separating blocks of code in Python. Name errors arise when variables are misspelled, and the interpreter can’t find the specified variable within the code’s scope.

Syntax errors are raised when the Python interpreter fails to understand the given commands by the programmer. In other words, when you make any spelling mistake or typos in your code, it will most definitely raise a syntax error.

It can also be raised when defining data types. For example, if you miss the last curly bracket, “}” when defining a dictionary or capitalize the “P” while trying to print an output, it will inevitably raise a syntax error or an exception.

In this article, we will take a look at one of the most common syntax errors. When trying to define dictionaries, there shouldn’t be any assignment operator, i.e., “=” between keys and values. Instead, you should put a colon , “:” between the two.

Let’s look at the root of the above problem followed by it’s solution.

Similar: Syntax Error: EOL while scanning string literal.

Python’s syntax errors can happen for many reasons, like using tabs and spaces incorrectly, spelling variables wrong, using operators the wrong way, or declaring things incorrectly. One common mistake is defining dictionaries wrongly by using “=” instead of “:” between keys and values. Fixing these issues usually means double-checking that everything is spelled right and that you are using things like colons, semicolons, and underscores properly.

There can be numerous reasons why you might encounter a syntax error in python. Some of them are:

  • When a keyword is misspelled.
  • If there are missing parenthesis when using functions, print statements, or when colons are missing at the end of for or while loops and other characters such as missing underscores(__) from def __innit__() functions.
  • Wrong operators that might be present at the wrong place.
  • When the variable declared is wrong or misspelled.

Differentiating between ‘=’ and ‘==’ in context of Python Dictionaries

In Python and many other programming languages, the single equals sign “=” denotes assignment, where a variable is given a specific value. In contrast, the double equals sign “==” is used to check for equality between two values or variables.

For example, if there are two variables, namely. ‘a’ and ‘b’ in your code, and you want to assign the integer values of 10 and 20 to each, respectively. In this case, you’ll need to use the assignment operator, that is, a single equal to sign(=) in your code in the following way:

a,b=10,20

But instead, if we want to check whether the values assigned to ‘a’ and ‘b’ are equal using an “if” statement, we will use the double equal to sign (==) such as,

if(a==b):

Syntax Rules for Python Dictionaries

In Python, dictionaries are a unique type of data-storing variables. They are ordered and mutable in nature unlike lists. They are assigned in pairs, in the form of keys and values. Each element in a dictionary is indexed by its’ keys. Each value is accessed by keeping track of its respective key. There should be a colon”:” separating the value from its respective key. They are represented by curly braces ‘{}’. Each key and value pair can be separated from one another with commas ‘,’.

They can be assigned in the following manner:

our_dictionary= {"key1": "value1",
"key2":"value2",
"key3":"value3",....}

Do check out: [SOLVED] ‘Unexpected Keyword Argument’ TypeError in Python.

Reproducing the Syntax Error: expression cannot contain assignment, perhaps you meant “==”?

In this case, the problem might arise when instead of using a colon “:”, the interpreter encounters an assignment operator. There is a built in function in Python that can explicitly convert data into dictionaries called dict(). But this function might also cause this problem when the identifier is wrong or when there are other syntax mistakes in the code, such as missing parenthesis at the end of a statement.

The error is shown below:

Reproducing The Error

Reproducing The Error

Mitigating Syntax Errors in Python Dictionaries

The only straight forward solution to this problem is making sure you spell the keywords and in built functions correctly and remember to use the identifiers such as colons, semicolons and underscores properly.

Try to avoid using the dict() function for creating dictionaries. Instead, use curly braces as much as possible. If using the function is a necessity, make sure you don’t use the assignment operator incorrectly and use parentheses where necessary.

In the following code, there are no exceptions raised because the syntax is correct and the variable has been assigned correctly.

our_dict = {1:'a', 2:'b', 3:'c', 4:'d'}

Nowadays, there are built in syntax detectors in IDEs and editors which can highlight syntax errors like this one. You can also use a debugger if necessary.

Key Takeaways: Avoiding Syntax Errors in Python Dictionaries

Having dived into the causes and solutions of Python’s syntax errors, we hope this equips you to write more efficient, error-free code. The intricacies of Python dictionaries need not be a source of worry. With the right practices, you can avoid these errors, optimizing your code and enriching your programming journey.

How will this knowledge influence your approach to using Python dictionaries in future projects?

Я создаю объект словаря, он создается, когда я использую «Заявление 1», однако я получаю сообщение об ошибке при попытке создать объект словаря, используя те же ключи и значения, что и в «Заявлении 2».

Утверждение 1

dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 
        4: 'Fri', 5: 'Sat', 6: 'Sun'}

Утверждение 2

dmap = dict(0='Mon', 1='Tue', 2='Wed', 3='Thu', 
            4='Fri', 5='Sat', 6='Sun'

Сообщение об ошибке:

    File "<stdin>", line 1
    SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

Может ли кто-нибудь сказать мне, почему мне разрешено создавать словарь с целочисленными ключами с помощью утверждения 1, но не с помощью утверждения 2?

< sizesОтредактировано Используя обновленную версию утверждения 2, я могу создать объект словаря с приведенным ниже кодом:

dmap = dict(day_0='Mon', day_1='Tue', day_2='Wed', 
            day_3='Thu', day_4='Fri', day_5='Sat', day_6='Sun')

Любая помощь приветствуется.

7 ответов

Лучший ответ

dict — это обычный вызываемый объект, который принимает аргументы ключевого слова. Согласно синтаксису Python аргументы ключевых слов имеют форму {{ X1}}. Идентификатор не может начинаться с цифры, что исключает числовые литералы.

keyword_item ::= identifier "=" expression

То, что dict по умолчанию создает словарь, который принимает произвольные ключи, не изменяет синтаксис вызовов.


3

MisterMiyagi
22 Авг 2020 в 16:54

Ваше замешательство, вероятно, связано с тем, что вы можете писать такие вещи, как:

d = dict(spam=1, eggs=2)

При этом используется функция, называемая «аргументы ключевого слова», и она работает, только если ключи являются строками. Следовательно, ваш пример не работает, потому что ключи — целые числа.


2

Brian McCutchon
22 Авг 2020 в 16:47

Потому что в утверждении 2 вы используете «=» вместо «:». вы должны использовать «:».

Правильно:

dict = {'a': 1, "b": 2, "c": 3}

Неправильный способ:

dict = {'a' = 1, "b" = 2, "c" = 3}

Так работает директория.


0

liad inon
22 Авг 2020 в 16:41

Словарь в Python должен содержать пару key-value. лайк

dmap = {0: ‘Пн’, 1: ‘Вт’, 2: ‘Среда’, 3: ‘Чт’, 4: ‘Пт’, 5: ‘Сб’, 6: ‘Вс’}

Здесь ключи — 0, 1, 2, 3, 4, 5, 6, а их соответствующие значения — 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'.
Примечание. Ключи или значения могут быть любого типа.

Но в заявлении 2: dmap = dict(0 = 'Mon', 1 = 'Tue', 2 = 'Wed', 3 = 'Thu', 4 = 'Fri', 5 = 'Sat', 6 = 'Sun') Вы присваиваете ценности. Это запрещено в питоне.

Вместо этого вы можете написать вот так.

dmap = dict({0 : 'Mon', 1 : 'Tue', 2 : 'Wed', 3 : 'Thu', 4 : 'Fri', 5 : 'Sat', 6 : 'Sun'})


-1

Dinesh
22 Авг 2020 в 16:44

В то время как 0:'Mon' изображает пару «ключ-значение» и оценивается как таковая, 0 = ‘Mon’ оценивается так, как если бы вы написали 0 = ‘Mon’ в обычном коде, который попытался бы присвоить ‘Mon’ числу. , а не переменная, и это было бы похоже на запись «Potato» = «Mon» — своего рода бессмысленный.


0

Dustin
22 Авг 2020 в 16:42

Вы можете использовать целые числа в качестве ключа в функции dict, но не так, вы можете сделать это следующим образом:

dmap = dict([(0 ,'Mon') ,(1, 'Tue'), (2, 'Wed'), (3, 'Thu'),(4, 'Fri'),(5 , 'Sat'), (6, 'Sun')])


0

Reza
22 Авг 2020 в 17:02

Возможно, вам также будет интересно:

  • Ошибка expression cannot be used as a function
  • Ошибка explorer в модуле kernelbase dll
  • Ошибка explorer exe черный экран
  • Ошибка explorer exe сбойный модуль ntdll dll
  • Ошибка explorer exe приложение не найдено

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии