I have created a dictionary d below and am looking for a dictionary with the key ('a','b','c') to have values 'd' and 'e'.
test = ['a','b','c','d','a','b','c','e','p','q','r','s']
test2= tuple(test)
d = {test2[i:i+3]:test2[i+3] for i in range(0,len(test2)-3,1)}
print(d)
The output is:
{('a', 'b', 'c'): 'e', ('b', 'c', 'd'): 'a', ('c', 'd', 'a'): 'b', ('d', 'a', 'b'): 'c', ('b', 'c', 'e'): 'p', ('c', 'e', 'p'): 'q', ('e', 'p', 'q'): 'r', ('p', 'q', 'r'): 's'}
The intended output is:
{('a', 'b', 'c'): ('d','e'), ('b', 'c', 'd'): 'a', ('c', 'd', 'a'): 'b', ('d', 'a', 'b'): 'c', ('b', 'c', 'e'): 'p', ('c', 'e', 'p'): 'q', ('e', 'p', 'q'): 'r', ('p', 'q', 'r'): 's'}
Question: Looking at the first comment, the key takes its most recent value e and so now I'm trying to change the code to achieve the desired output? Thanks.
Option 1:
This create d using defaultdict (d = defaultdict(list)).
It loops through the data in a for loop. Multiple values are appended into a list
from collections import defaultdict
d = defaultdict(list) # create list by default
for i in range(0,len(test2)-3):
d[test2[i:i+3]].append(test2[i+3]) # append value into dictionary entry
# which is a list
# since we used d = defaultdict(list)
Option 2: Similar in form to option 1, but uses normal dictionary with setdefault to have key entries be lists
d = {}
for i in range(0,len(test2)-3):
d.setdefault(test2[i:i+3], []).append(test2[i+3])
Both Options Have the Same Output
defaultdict(<class 'list'>,
{ ('a', 'b', 'c'): ['d', 'e'],
('b', 'c', 'd'): ['a'],
('b', 'c', 'e'): ['p'],
('c', 'd', 'a'): ['b'],
('c', 'e', 'p'): ['q'],
('d', 'a', 'b'): ['c'],
('e', 'p', 'q'): ['r'],
('p', 'q', 'r'): ['s']})
Heres a another solution you can try out as well:
from collections import defaultdict
test = ['a','b','c','d','a','b','c','e','p','q','r','s']
d = defaultdict(list)
while len(test) >= 4:
*key, value = test[:4] # key -> a, b, c value -> d
d[tuple(key)].append(value)
test = test[1:]
print(d)
# defaultdict(<class 'list'>, {('a', 'b', 'c'): ['d', 'e'], ('b', 'c', 'd'): ['a'], ('c', 'd', 'a'): ['b'], ('d', 'a', 'b'): ['c'], ('b', 'c', 'e'): ['p'], ('c', 'e', 'p'): ['q'], ('e', 'p', 'q'): ['r'], ('p', 'q', 'r'): ['s']})
The basic idea is that it keeps shrinking the list test
until less than 4 items are left, and groups the first three items (a, b, c)
into a tuple, then the last character d
as a value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.