How to Add Multiple Values to a Dictionary Key

append multiple values for one key in a dictionary

If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:

years_dict = dict()

for line in list:
if line[0] in years_dict:
# append the new number to the existing array at this slot
years_dict[line[0]].append(line[1])
else:
# create a new array in this slot
years_dict[line[0]] = [line[1]]

What you should end up with in years_dict is a dictionary that looks like the following:

{
"2010": [2],
"2009": [4,7],
"1989": [8]
}

In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.

How to add multiple values per key in python dictionary

The value for each key can either be a set (distinct list of unordered elements)

cat1 = {"james":{1,2,3}, "bob":{3,4,5}}
for x in cat1['james']:
print x

or a list (ordered sequence of elements )

cat1 = {"james":[1,2,3], "bob":[3,4,5]}
for x in cat1['james']:
print x

Add multiple values to a dictionary key

Use defaultdict :

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for i,key in enumerate(list1):
if list2[i] not in d[key]: #to add only unique values (ex: '693':'goa')
d[key].append(list2[i])

>>> d
=> defaultdict(<class 'list'>, {'670': ['JAIPUR', 'UDAIPUR'], '619': ['MUMBAI'],
'524': ['DELHI'], '693': ['GOA'], '632': ['LUCKNOW'], '671': ['JAIPUR']})

How to add multiple values ​to a dictionary key

As @SauravPathak says, you want to read in the JSON file from the previous run to reconstruct your data structure in memory, add the current set of data to that, and then save the data structure back out to the file. Here's roughly the code you'd need to do that:

import json
import os

output_path = '/tmp/report.json'

def add_daily_vaules(file):

# Read in existing data file if it exists, else start from empty dict
if os.path.exists(output_path):
with open(output_path) as f:
product_prices_date = json.load(f)
else:
product_prices_date = {}

# Add each of today's products to the data
for products_details in file:
title = products_details['title']
price = products_details['price']
date = products_details['date']
# This is the key - you want to append to a prior entry for a specific
# title if it already exists in the data, else you want to first add
# an empty list to the data so that you can append either way
if title in product_prices_date:
prices_date = product_prices_date[title]
else:
prices_date = []
product_prices_date[title] = prices_date
prices_date.append({date:price})

# Save the structure out to the JSON file
with open(output_path, "w") as f:
json.dump(f, product_prices_date)

How to add multiple values of same key in python dictionary

dict1 = {'key1': [1,2,3,4] , 'key2': [5,6,7]}
{k:sum(v) for k,v in dict1.items()}

First your extract the keys and values from your dictionary, then you sum the values as output.

dict1.items()
dict_items([('key1', [1, 2, 3, 4]), ('key2', [5, 6, 7])])

As you can see you get a tuple. By saying for k,v in dict1.items(), you are extracting those k,v then you are summing the v...
Hope you understand.

c# dictionary How to add multiple values for single key?

Update: check for existence using TryGetValue to do only one lookup in the case where you have the list:

List<int> list;

if (!dictionary.TryGetValue("foo", out list))
{
list = new List<int>();
dictionary.Add("foo", list);
}

list.Add(2);



Original:
Check for existence and add once, then key into the dictionary to get the list and add to the list as normal:

var dictionary = new Dictionary<string, List<int>>();

if (!dictionary.ContainsKey("foo"))
dictionary.Add("foo", new List<int>());

dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);

Or List<string> as in your case.

As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>, favour the constructor that takes the initial list capacity: new List<int>(100);.

This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.

How to add multiple values in dictionary for a key

here if you want to add multiple numbers

a_list = []
a_dict = {'Number': a_list}

#here so the will loop will be runing
RUN = True

while RUN:
a = int(input('Enter a number: '))
l = a_list.append(a)
quit_the_while = input('Enter q to quit or any thing to add more number: ')
if 'q' in quit_the_while:
break
else:
continue

print(a_dict)

here for 3 numbers only

a_list = []
a_dict = {'Number': a_list}

while len(a_list) < 3:
a = int(input('Enter a number: '))
l = a_list.append(a)

print(a_dict)

How to add multiple values to a key in a Python dictionary

Dictionary, associative array or map (many names, basically the same functionality) property is that keys are unique.

The keys you wish to have, which are integers, are not unique if lengths are the same, that's why your code doesn't work. Putting a new value for existing key means replacing the old value.

You have to add key-value pairs to the existing value dictionaries.

for mykey in name_num:
length = len(name_num[mykey])
if length in new_dict: # key already present in new dictionary
new_dict[length][mykey] = name_num[mykey]
else:
new_dict[length] = {mykey: name_num[mykey]}

should do the trick



Related Topics



Leave a reply



Submit