Python Forum
dict elements are sometimes treated as List and sometimes as String
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dict elements are sometimes treated as List and sometimes as String
#1
I'm just learning Python by developing an anagram finder.

After a bit of debugging it seems that if I check "if token not in words" then the words dictionary treats its elements as List items.

But if I assign a value without doing the "if" check, the values are treated as Strings (rather than a List of strings).

Is there somewhere I can research why the behavior changes? Is there a way to force the dictionary to make the values Lists?

I'm using PyCharm 2019.3.4 for Mac with Python 3.7.2

# This code block treats words[] values as List items, allowing append to work
words = dict()
token: str ="acto"
if token not in words:
    words[token] = ["coat"]
else:
    words[token].append("coat")

words[token].append("taco") #In this code block, "taco" is appended to the List associated with the "acto" key -> ['coat', 'taco']

for x in words:
    print (words[x])
# This code block treats words[] values as Strings items.  Append does not work
words = dict()
token: str ="acto"
words[token] = ["coat"]
words[token].append("taco") #blows up because String has no append method.
Reply


Messages In This Thread
dict elements are sometimes treated as List and sometimes as String - by phython_mdr - Mar-29-2020, 05:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 590 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 564 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Checking if a string contains all or any elements of a list k1llcod3 1 1,249 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 2,151 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,304 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 1,537 May-31-2022, 08:43 PM
Last Post: Gribouillis
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,405 May-17-2022, 11:38 AM
Last Post: Larz60+
  Updating nested dict list keys tbaror 2 1,353 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Why am I getting list elements < 0 ? Mark17 8 3,295 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 2,224 Aug-19-2021, 12:05 PM
Last Post: Alex_James

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020