'How to append tuples to a dictionary without list or having brackets around it
I have the following code:
G = {
'A': {('1', 2), ('C', 5)},
'B': {('C', 6), ('D', 1), ('E', 3), ('A', 2)},
'C': {('F', 8), ('A', 5), ('B', 6)},
'D': {('E', 4)},
'E': {('G', 9)},
'F': {('G', 7), ('C', 2)},
'G': {('E', 9), ('F', 7)}
}
Say I want to replace the nested dict key 'A' values with ('D', 7), ('E', 8) using a for loop, my approach was to append each of the tuple into a list and then G['A'] = list but this would give me 'A': {[('D', 7), ('E', 8)]} with brackets ([,]) within
Is there a way to append tuples into a dictionary such that without having brackets
Solution 1:[1]
Clear the existing (i.e. G['A'] = set()) or if you want to remove some, use .remove.
And, use .add to add a value because the values of the dict are sets.
G['A'] = set()
G['A'].add(('D', 7))
G['A'].add(('E', 8))
output:
{'A': {('D', 7), ('E', 8)},
'B': {('A', 2), ('C', 6), ('D', 1), ('E', 3)},
'C': {('A', 5), ('B', 6), ('F', 8)},
'D': {('E', 4)},
'E': {('G', 9)},
'F': {('C', 2), ('G', 7)},
'G': {('E', 9), ('F', 7)}}
Alternatively, you could assign a key directly to a set literal, as:
G['A'] = {('D', 7), ('E', 8)}
The difference between a dict and a set is that while both use curly braces { }, dictionaries have key:value pairs (like G does), while sets only have values. This is why the value of G['A'] is a set and not a nested dict.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quack E. Duck |
