You're looking for Python Dictionaries.
sample = {}
for i in range(6):
# some code that gives you x
sample[i] = x
print(sample)
Do note, however, that since your keys are just 0, 1, 2 etc., you may want to just use a list instead:
sample = []
for i in range(6):
# some code that gives you x
sample.append(x)
print(sample)
Note that dictionary access using sample[key] will look identical to list access using sample[index] since you're just using consecutive numeric keys.
You're looking for Python Dictionaries.
sample = {}
for i in range(6):
# some code that gives you x
sample[i] = x
print(sample)
Do note, however, that since your keys are just 0, 1, 2 etc., you may want to just use a list instead:
sample = []
for i in range(6):
# some code that gives you x
sample.append(x)
print(sample)
Note that dictionary access using sample[key] will look identical to list access using sample[index] since you're just using consecutive numeric keys.
Is this what you are looking for?
dic = {}
x = "8"
for i in range(6):
#calculate x
dic[i] = int(str(x)+str(i))
print(dic)
{0: 80, 1: 81, 2: 82, 3: 83, 4: 84, 5: 85}
python 3.x - How to add key and value pairs to new empty dictionary using for loop? - Stack Overflow
python - Adding item to Dictionary within loop - Stack Overflow
python - How can I add new keys to a dictionary? - Stack Overflow
Looping through Dictionary and add items to second dictionary
Hello, I'm trying to compare the kappa scores for one person against other people. I want to generate a dataframe that has the kappa for person A vs person B, person A vs person C, person A vs person D, etc.
To do this, I was thinking of reading in a everyone's scores that they gave as a dataframe, and assigning them to a dictionary. So something like {person B : person_B_scores_df, person C: person_C_scores}
But I can't figure out how to iterate over a for loop and add the key pairings to a dictionary. I keep getting a key error. Here is my code.
## Create list of raters
rater_list = ["person_A", "person_B", "person_C", "person_D"]
rater_dict = {}
## Pull in each rater's scores and add them key/value pairing in rater_dict
for name in rater_list:
rater_df = pd.read_csv(input_path/f"rater_scores_{name}.csv")
rater_dict[name].append(rater_df)
## Also tried the following!! - The code below only appends the last person in the rater list to the dictionary
#for name in rater_list:
# rater_df = pd.read_csv(input_path/f"rater_scores_{name}.csv")
# rater_dict={name:rater_df}In Python, dictionary keys are unique. If you assign a value to the same key again, it gets overwritten. Example :
dct = {}
dct["key"] = "value"
print(dct)
dct["key"] = "value2"
print(dct)
Output :
{"key": "value"}
{"key": "value2"}
The only option you have is to create a list of amounts and a list of ids:
new_debt_dic = {"amounts": [], "ids": []}
for i in debts_list:
new_debt_dic["amounts"].append(i["amount"])
new_debt_dic["ids"].append(i["id"])
print(new_debt_dic)
Output :
{"amounts": [123.46, 100, ...], "ids": [0, 1, ...]}
Each value of debts_list is dictionary with only 2 key-value pairs, where the keys are amount or id. I think you meant to use the id as your keys - if so, you should use the following:
new_debt_dic = {}
for d in debts_list:
new_debt_dic[d['id']] = d['amount']
In your current code, what Dictionary.update() does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.
If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list as a list and then append case to it (instead of update) .
Example -
case_list = []
for entry in entries_list:
case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
case_list.append(case)
Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1 or entry2 , etc and the value being the corresponding dictionary for that entry.
case_list = {}
for entry in entries_list:
case = {'key1': value, 'key2': value, 'key3':value }
case_list[entryname] = case #you will need to come up with the logic to get the entryname.
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
You create a new key/value pair on a dictionary by assigning a value to that key
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.
I feel like consolidating info about Python dictionaries:
Creating an empty dictionary
data = {}
# OR
data = dict()
Creating a dictionary with initial values
data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}
Inserting/Updating a single value
data['a'] = 1 # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)
Inserting/Updating multiple values
data.update({'c':3,'d':4}) # Updates 'c' and adds 'd'
Python 3.9+:
The update operator |= now works for dictionaries:
data |= {'c':3,'d':4}
Creating a merged dictionary without modifying originals
data3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
Python 3.5+:
This uses a new feature called dictionary unpacking.
data = {**data1, **data2, **data3}
Python 3.9+:
The merge operator | now works for dictionaries:
data = data1 | {'c':3,'d':4}
Deleting items in dictionary
del data[key] # Removes specific element in a dictionary
data.pop(key) # Removes the key & returns the value
data.clear() # Clears entire dictionary
Check if a key is already in dictionary
key in data
Iterate through pairs in a dictionary
for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys
Create a dictionary from two lists
data = dict(zip(list_with_keys, list_with_values))