Python Forum

Full Version: Converting List of 3 Element Tuple to Dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I have one 3d list of tuple

list=[(0, 1, 6), (5,1,4), (1, 6, 0), (3, 2,1),(4,5,1)]
I want to add in a dictionary like this:

{ (0,1,6): 2,
  (4,5,1): 2,
  (3,2,1): 1 }
I want to count the similar tuples.

Any suggestions?
What have you tried?

If this is homework you would probably use the get method of the dictionary with 0 as the default, otherwise use collections.Counter.
What should I enter for key?
What do you think? Look at the sample output dictionary in your original post.
If you don't have to implement your own Counter, you can use the Counter from the collections module.
As mentioned before, tuples are immutable and hashable objects, which can be used as keys for a dict.

In your case, it's just Counter(your_list).
Btw. you've used list as a name for the list. list is a type and you've overwritten it with your list.
Give it another name.
mylist = [(x,y,z) for x in range(1,7) for y in range(1,7) for z in range(1,7)]
count=0
combs=[]
counts = dict()
for data in mylist:
            if data not in counts:
                counts[data] =1
            else :
                counts[data]=counts[data]+1

print(counts)
The problem here is that all the data take value:1 and it is not increment?
(Jan-11-2019, 02:38 AM)fooikonomou Wrote: [ -> ]The problem here is that all the data take value:1 and it is not increment?

All the tuples in mylist are unique, so all of the values would be 1. It looks like you want all of the sorted combinations, so you need to sort them before checking/incrementing counts.
And how this can be done?
Let's say I have this list:
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 1, 5), (1, 1, 6), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 1), (1, 3, 2), (1, 3, 3), (1, 3, 4), (1, 3, 5), (1, 3, 6), (1, 4, 1), (1, 4, 2), (1, 4, 3), (1, 4, 4), (1, 4, 5), (1, 4, 6), (1, 5, 1), (1, 5, 2), (1, 5, 3), (1, 5, 4), (1, 5, 5), (1, 5, 6), (1, 6, 1), (1, 6, 2), (1, 6, 3), (1, 6, 4)....]

how to sort the tuple values form ex: (6,1,5) --> to (1,5,6)?
(Jan-11-2019, 01:13 PM)fooikonomou Wrote: [ -> ]how to sort the tuple values form ex: (6,1,5) --> to (1,5,6)?

Like with built-in function sorted()? Note, that it will return list, not tuple (tuples are immutable).

>>> t = (6, 1, 5)
>>> sorted(t)
[1, 5, 6]
It you need tuple, then you can just convert it back tuple(sorted(t))
The function sorted can sort also a list of lists / list of tuples.

If you want to sort the content of the tuples, you can make a new list. You can use a list comprehension.

The first example sorts the content of the list.
The second example keeps the order of the list and sorts the content of the tuples.
Pages: 1 2