Python Forum
Dictionary and tuples list comprehensions help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary and tuples list comprehensions help
#1
Hi I have a dictionary with keys and values and I am wanting to convert these into a list of tuples.

Dictionary = {'(A,B):1,'(C,D)':2}

Note that the keys are currently tuples. I basically want to add the value to the key tuples to form the following format:

TuplesList = [(A,B,1), (C,D,2)]

I have made an attempt at doing this using the following;

TuplesList = [k,v) for k, v in Dictionary.items()]

However, this is giving me the incorrect output of;
TuplesList = [(('A','B'),1),(('C','D'),2)]

Any advice would be appreciated on how I can get my desired output. Thank you
Reply
#2
tuples_list = [k + (v,) for k, v in Dictionary.items()]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Desired output with tuple unpacking:

>>> d = {('spam', 'ham'): 1, ('eggs', 'bacon'): 2}
>>> [(*k, v) for k, v in d.items()]
[('spam', 'ham', 1), ('eggs', 'bacon', 2)]
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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dictionary in a list bashage 2 539 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 666 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Sort a list of dictionaries by the only dictionary key Calab 1 488 Oct-27-2023, 03:03 PM
Last Post: buran
  How to add list to dictionary? Kull_Khan 3 998 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  Adding values with reduce() function from the list of tuples kinimod 10 2,632 Jan-24-2023, 08:22 AM
Last Post: perfringo
  convert this List Comprehensions to loop jacklee26 8 1,502 Oct-21-2022, 04:25 PM
Last Post: deanhystad
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 1,450 May-31-2022, 08:43 PM
Last Post: Gribouillis
  check if element is in a list in a dictionary value ambrozote 4 1,962 May-11-2022, 06:05 PM
Last Post: deanhystad
  Dictionary from a list failed, help needed leoahum 7 1,955 Apr-28-2022, 06:59 AM
Last Post: buran
  how to assign items from a list to a dictionary CompleteNewb 3 1,564 Mar-19-2022, 01:25 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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