Python Forum
dict value, how to change type from int to list?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dict value, how to change type from int to list?
#4
One way is to use setdefault.

>>> test = dict()
>>> test.setdefault('key1', list()).append(2)
>>> test
{'key1': [2]}
It could be used in for-loops etc:

>>> test = dict()
>>> nums = [2, 3, 7, 19, 24]
>>> for num in nums:
...     if num % 2:
...         test.setdefault(num, list()).append(num**2)
...
>>> test
{3: [9], 7: [49], 19: [361]}
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: dict value, how to change type from int to list? - by perfringo - Dec-09-2020, 09:50 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Change font in a list or tuple apffal 4 2,635 Jun-16-2023, 02:55 AM
Last Post: schriftartenio
  How to change the datatype of list elements? mHosseinDS86 9 1,912 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  search a list or tuple for a specific type ot class Skaperen 8 1,855 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  TypeError: unsupported operand type(s) for +: 'dict' and 'int' nick12341234 1 9,208 Jul-15-2022, 04:04 AM
Last Post: ndc85430
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,162 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  find some word in text list file and a bit change to them RolanRoll 3 1,482 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 1,415 May-31-2022, 08:43 PM
Last Post: Gribouillis
  TypeError: unsupported opperand type(s) for %: 'int' and 'list' cool_person 7 2,099 May-07-2022, 08:40 AM
Last Post: ibreeden
  unsupported operand type(s) for %: 'list' and 'int' RandomCoder 4 32,709 May-07-2022, 08:07 AM
Last Post: menator01
  Updating nested dict list keys tbaror 2 1,243 Feb-09-2022, 09:37 AM
Last Post: tbaror

Forum Jump:

User Panel Messages

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