Questions tagged [fromkeys]
7 questions
15
votes
3 answers
How do I create a unique value for each key using dict.fromkeys?
First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use dict.fromkeys (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and…

Kyle Cronin
- 77,653
- 43
- 148
- 164
2
votes
3 answers
python dict.fromkeys() returns empty
I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.
def…

slooow
- 329
- 1
- 3
- 10
1
vote
1 answer
Adding to only one list in dictionary
def stack_ov_test():
my_set = set([1, 2, 1, 2, 3, 4, 3, 2, 3])
my_dictionary = dict.fromkeys(my_set, [])
my_dictionary[1].append(0)
print(my_dictionary) # {1: [0], 2: [0], 3: [0], 4: [0]}
I think the code above is pretty much…

Adrian
- 363
- 3
- 12
1
vote
2 answers
Counting in a python nested dictionary | fromkeys() function How it works?
Given a list of runs up to a maximum reached stage, I would like to transfer the maximum values to a nested dictionary holding the number of tries (t) for each stage.
This means runs of 3, 4 and 7 should yield:
{0: {'t': 3}, 1: {'t': 3}, 2: {'t':…

Frank
- 11
- 2
0
votes
2 answers
How to create new dictionary by selecting particular keys using fromkey() in python Dictionary?
I created the dictionary named as Colors.
Colors = {'col1': 'Red', 'col2': 'Orange', 'col3': 'Yellow', 'col4': 'Yellow'}
Q) Create a new Dictionary object colors_new from the colors Dictionary, having the keys col1 and col2 (Instruction – Use the…

SHENBGA BHARATHA PRIYA
- 49
- 11
0
votes
1 answer
Constructing a Python dict with lists as values - why does seemingly equivalent code gives different results?
I wish to construct a Python dict from the keys of another dict and build new lists to use as the dict values. I have written two pieces of code which I thought would be equivalent but are not.
The first piece of code I prefer since it doesn't use a…

Dave
- 312
- 3
- 11
-2
votes
1 answer
Using fromkeys to create a dictionary
I am writing in Python
I have a list of tuples called 'positions'. Some of these tuples have more than 1 occurence in 'positions'. I want to create a dictionary named d with the code:
d["positions"] = dict.fromkeys(positions)
This gives me a…

Alexander Ameye
- 175
- 1
- 1
- 8