list to dictionary conversion with multiple values per key?
from collections import defaultdict
d1 = defaultdict(list)
for k, v in l:
d1[k].append(v)
d = dict((k, tuple(v)) for k, v in d1.items())
d
contains now {1: ('A', 'B'), 2: ('C',)}
d1
is a temporary defaultdict with lists as values, which will be converted to tuples in the last line. This way you are appending to lists and not recreating tuples in the main loop.
Handling a dictionary with multiple values per key
You almost had it, you need to create a list for each key and then just append the timestamps.
Try this:
team2goals = {}
<loop through list>
timestamp = xValue
if name not in team2goals:
team2goals[name] = []
team2goals[name].append(timestamp)
Converting list of lists to a dictionary with multiple values for a key
You can iterate through the key-value pairs in the list of lists, but unpack the value as a list to accommodate the possible lack of a value:
s = [['A','B'],['A','C'],['A','D'],['B','A'],['C','B'],['C','D'],['D','B'],['E']]
output = {}
for k, *v in s:
if v:
output.setdefault(k, []).extend(v)
else:
output[k] = None
output
becomes:
{'A': ['B', 'C', 'D'], 'B': ['A'], 'C': ['B', 'D'], 'D': ['B'], 'E': None}
Or if you don't mind that keys without a value get an empty list instead of None
, you can simply do:
output = {}
for k, *v in s:
output.setdefault(k, []).extend(v)
output
would then become:
{'A': ['B', 'C', 'D'], 'B': ['A'], 'C': ['B', 'D'], 'D': ['B'], 'E': []}
List of dictionaries with multiple values per key as Dataframe
pd.DataFrame(d).stack().apply(
pd.Series).add_prefix(
'Value').reset_index().rename(columns={'level_0':'index', 'level_1':'Date'})
Output
index Date Value0 Value1 Value2 Value3
0 0 2020-12-31 00:00:00 123 456 789 321
1 1 2021-05-06 00:00:00 999 888 777 666
How convert multiple keys into single of dictionary and create Dictionary with multiple values per key in python
I think this is what you're looking for:
d = {
"Parameter_1": {
"2021-11-16 14:29:00": 319.56,
"2021-11-16 15:16:00": 319.56,
"2021-11-16 15:17:00": 319.56,
"2021-11-17 00:00:00": 335.48,
"2021-11-17 00:01:00": 335.48,
"2021-11-17 00:02:00": 335.48,
"2021-11-18 00:00:00": 355.45,
"2021-11-18 00:01:00": 355.45,
"2021-11-18 00:03:00": 355.45,
},
"Parameter_2": {
"2021-11-16 14:29:00": 319.56,
"2021-11-16 15:16:00": 319.56,
"2021-11-16 15:17:00": 319.56,
"2021-11-17 00:00:00": 335.48,
"2021-11-17 00:01:00": 335.48,
"2021-11-17 00:02:00": 335.48,
"2021-11-18 00:00:00": 355.45,
"2021-11-18 00:01:00": 355.45,
"2021-11-18 00:03:00": 355.45,
}}
r = dict()
for k, v in d.items():
r[k] = dict()
for k_, v_ in v.items():
r[k].setdefault(k_[:10], []).append(v_)
print(r)
Output:
{'Parameter_1': {'2021-11-16': [319.56, 319.56, 319.56], '2021-11-17': [335.48, 335.48, 335.48], '2021-11-18': [355.45, 355.45, 355.45]}, 'Parameter_2': {'2021-11-16': [319.56, 319.56, 319.56], '2021-11-17': [335.48, 335.48, 335.48], '2021-11-18': [355.45, 355.45, 355.45]}}
Merge two lists into one dict that may contain several values for each key
Python does not have multidicts, so you have two options:
use multidicts from an existing library e.g. werkzeug's
MultiDict
, when initialised with lists of pairs, will associate multiple values to keys which are present multiple times (unlike dict which will only keep the last value)system_data_dict = werkzeug.datastructures.MultiDict(zip(system, instrument))
system_data_dict.getlist('System A') # => ['Instrument 1', 'Instrument 2']alternatively, do that by hand by using a regular loop, even if it's feasible using a comprehension (which I'm not sure about) it's going to look dreadful: use a
defaultdict
or thedict.setdefault
method to define a dict mapping keys to lists and append values every timesystem_data_dict = {}
for k, v in zip(system, instrument):
system_data_dict.setdefault(k, []).append(v)
system_data_dict['System A'] # => ['Instrument 1', 'Instrument 2']
Python convert list to dict with multiple key value
Several ways to do this, this is one:
EDIT: my first solution gave a list for every value, but you only require a list when there is more than one value for a key.
my_list = ['key1=value1', 'key2=value2', 'key3=value3-1', 'value3-2', 'value3-3', 'key4=value4', 'key5=value5', 'value5-1', 'value5-2', 'key6=value6']
my_dict = {}
current_key = None
for item in my_list:
if '=' in item:
current_key, value = item.split('=')
# This puts a string as the value
my_dict[current_key] = value
else:
# Check if the value is already a list
if not isinstance(my_dict[current_key], list):
# If value is not a list, create one
my_dict[current_key] = [my_dict[current_key]]
my_dict[current_key].append(item)
import pprint
pprint.pprint(my_dict)
Gives:
{'key1': 'value1',
'key2': 'value2',
'key3': ['value3-1', 'value3-2', 'value3-3'],
'key4': 'value4',
'key5': ['value5', 'value5-1', 'value5-2'],
'key6': 'value6'}
You might wish to make it more robust by checking if current_key
is None
. I'll leave that to you.
Convert list of tuples of several values into dictionary in Python 3.8
My approach is bit different, probably you can checkout this answer too:
user_list = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]
final = {}
for item in user_list:
final.update(
{
item[0]: [item[1]] + final[item[0]] if final.get(item[0]) else [item[1]]
}
)
print(final)
output: {'a': [2, 3, 1], 'b': [1, 2], 'c': [1]}
Related Topics
How to Compute the Intersection Point of Two Lines
Converting String with Utc Offset to a Datetime Object
Creating a Pandas Dataframe from a Numpy Array: How to Specify the Index Column and Column Headers
Pandas - Plotting a Stacked Bar Chart
Recommendations of Python Rest (Web Services) Framework
Python3: Importerror: No Module Named '_Ctypes' When Using Value from Module Multiprocessing
Django 1.7 Throws Django.Core.Exceptions.Appregistrynotready: Models Aren't Loaded Yet
Thread Starts Running Before Calling Thread.Start
How to Print Unicode Character in Python
How to Use Argsort in Descending Order
Finding Indices of Matches of One Array in Another Array
Replacing Column Values in a Pandas Dataframe