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}
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']
key is just a variable name.
for key in d:
will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:
For Python 3.x:
for key, value in d.items():
For Python 2.x:
for key, value in d.iteritems():
To test for yourself, change the word key to poop.
In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better.
This is also available in 2.7 as viewitems().
The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).
It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.
In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write
for k in dict: ...which is equivalent to, but much faster than
for k in dict.keys(): ...as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of iterators explicitly:
for key in dict.iterkeys(): ... for value in dict.itervalues(): ... for key, value in dict.iteritems(): ...This means that
for x in dictis shorthand forfor x in dict.iterkeys().
In Python 3, dict.iterkeys(), dict.itervalues() and dict.iteritems() are no longer supported. Use dict.keys(), dict.values() and dict.items() instead.
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))
Use dictionary assignment:
for row in iterable:
Eg_dict[row[1]] = row[2]
or ever replace the whole code with a dict comprehension:
Eg_dict = {row[1]: row[2] for row in iterable} # python 2.7 and up
or
Eg_dict = dict(row[1:3] for row in iterable) # python 2.3 and up
If each row has a fixed number of entries, you can use tuple assignment:
for key, value in row: # two elements
or
for _, key, value in row: # three elements, ignore the first
to make a loop more readable. E.g. {key: value for _, key, value in iterable}.
Your code instead creates a new set object (just unique values, no keys) each loop, replacing the previous one.
You can use a nice list comprehension for this:
d = dict([(row[1], row[2]) for row in iterable])
This will work in any Python version.
If you use 2.7+ or 3, you can use the cleaner dict comprehension:
d = {row[1]:row[2] for row in iterable}