How would I make a list of tuples of size three into key-value pairs?
Clash Royale CLAN TAG#URR8PPP
How would I make a list of tuples of size three into key-value pairs?
Objective:
1st number: Key to the second number
2nd number: Value to the first number but key to the third number
3rd number: Value to the second number
def make_dictionary_list(old_list):
return key: values for key, *values in old_list
Input: [(4157, 1, 1), (4157, 1, 10), (4157, 2, 1), (4157, 2, 10), (4157, 3, 1), (4157, 3, 10), (4157, 4, 1), (4157, 4, 10), (4182, 1, 1)]
[(4157, 1, 1), (4157, 1, 10), (4157, 2, 1), (4157, 2, 10), (4157, 3, 1), (4157, 3, 10), (4157, 4, 1), (4157, 4, 10), (4182, 1, 1)]
Output:4157: [4, 10], 4182: [1, 1]
4157: [4, 10], 4182: [1, 1]
The output is not what I want. As stated above, I'd like the 1st number being key to the 2nd number and 2nd number being the key to the 3rd number. How would I go about doing that?
Thanks!
1 Answer
1
You unravel your list:
data = [(4157, 1, 1), (4157, 1, 10), (4157, 2, 1), (4157, 2, 10), (4157, 3, 1), (4157, 3, 10), (4157, 4, 1), (4157, 4, 10), (4182, 1, 1)]
d =
for k,v,p in data:
key = d.setdefault(k,)
key[v]=p
print(d)
Output:
4157: 1: 10, 2: 10, 3: 10, 4: 10, 4182: 1: 1
The result is shorter then your sourcedata because you redefine the values of your inner dict for:
(4157, 1, 1) => (4157, 1, 10)
(4157, 2, 1) => (4157, 2, 10)
(4157, 3, 1) => (4157, 3, 10)
(4157, 4, 1) => (4157, 4, 10)
The first value gets replaced by the second one. You could aggregate them like so:
for k,v,p in data:
key = d.setdefault(k,)
key2 = key.setdefault(v,)
key2.append(p)
print(d)
To get an output of:
4157: 1: [1, 10], 2: [1, 10], 3: [1, 10], 4: [1, 10], 4182: 1: [1]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
you have duplicate keys.
– Garr Godfrey
5 mins ago