I'm trying to build a dict comprehension that does an insert and takes a slice.
Does anybody know how to do this, or even is this is possible at all?
I'm trying to get the same output in cprd
with a dict comprehension, as in newd
with a for loop.
Code (Python 3.6.1)
# Initializations
hline = "-"*80
h = ['H1', 'H2', 'H3', 'H4']
d = {'A': [['Y1', 'Y2', 'Y3', 'Y4'], [-3.4, 15.9, 'NA', 6.0], [-3.4, 4.2, -7.4, 6.3], [22.7, 7.4, 2.8, 'NA']], 'B': [['Y1', 'Y2', 'Y3', 'Y4'], [-45.8, -10.7, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']], 'C': [['Y1', 'Y2', 'Y3', 'Y4'], [-10.5, 32.8, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']]}
print(f"h = {h}")
print(f"d = {d}")
print(hline)
# Without dict/list comprehension
newd = {}
for key,value in d.items():
value.insert(1,h)
newd[key] = value[1:]
print(f"newd = {newd}")
print(hline)
# Re-Initializations
d = {'A': [['Y1', 'Y2', 'Y3', 'Y4'], [-3.4, 15.9, 'NA', 6.0], [-3.4, 4.2, -7.4, 6.3], [22.7, 7.4, 2.8, 'NA']], 'B': [['Y1', 'Y2', 'Y3', 'Y4'], [-45.8, -10.7, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']], 'C': [['Y1', 'Y2', 'Y3', 'Y4'], [-10.5, 32.8, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']]}
# Tryout with dict comprehension
cprd = {key:value[1:] for key,value in d.items()}
print(f"cprd = {cprd}")
print(hline)
Output
h = ['H1', 'H2', 'H3', 'H4']
d = {'A': [['Y1', 'Y2', 'Y3', 'Y4'], [-3.4, 15.9, 'NA', 6.0], [-3.4, 4.2, -7.4, 6.3], [22.7, 7.4, 2.8, 'NA']], 'B': [['Y1', 'Y2', 'Y3', 'Y4'], [-45.8, -10.7, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']], 'C': [['Y1', 'Y2', 'Y3', 'Y4'], [-10.5, 32.8, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']]}
--------------------------------------------------------------------------------
newd = {'A': [['H1', 'H2', 'H3', 'H4'], [-3.4, 15.9, 'NA', 6.0], [-3.4, 4.2, -7.4, 6.3], [22.7, 7.4, 2.8, 'NA']], 'B': [['H1', 'H2', 'H3', 'H4'], [-45.8, -10.7, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']], 'C': [['H1', 'H2', 'H3', 'H4'], [-10.5, 32.8, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']]}
--------------------------------------------------------------------------------
cprd = {'A': [[-3.4, 15.9, 'NA', 6.0], [-3.4, 4.2, -7.4, 6.3], [22.7, 7.4, 2.8, 'NA']], 'B': [[-45.8, -10.7, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']], 'C': [[-10.5, 32.8, 'NA', 'NA'], [5.4, 12.7, 19.2, 20.3], [22.7, 7.4, 2.8, 'NA']]}
--------------------------------------------------------------------------------