How to Assign the Same Value to Multiple Keys in a Dict Object at Once

Is it possible to assign the same value to multiple keys in a dict object at once?

I would say what you have is very simple, you could slightly improve it to be:

my_dict = dict.fromkeys(['a', 'c', 'd'], 10)
my_dict.update(dict.fromkeys(['b', 'e'], 20))

If your keys are tuple you could do:

>>> my_dict = {('a', 'c', 'd'): 10, ('b', 'e'): 20}
>>> next(v for k, v in my_dict.items() if 'c' in k) # use .iteritems() python-2.x
10

This is, of course, will return first encountered value, key for which contains given element.

Dictionary with multiple keys mapping to same value

Is it what you want to achieve ?

int_dict = { 0              : "String1",
1 : "String2",
2 : "String3",
16 : "String5" };
#range is first inclusive last exlusif, watch out for that
for i in range(3,15) :
int_dict[i] = "String4"

output :

{0: 'String1',
1: 'String2',
2: 'String3',
3: 'String4',
4: 'String4',
5: 'String4',
6: 'String4',
7: 'String4',
8: 'String4',
9: 'String4',
10: 'String4',
11: 'String4',
12: 'String4',
13: 'String4',
14: 'String4',
16: 'String5'}

Edit : you can also use tuple as key

int_dict = { (0,0)              : "String1",
(1,1) : "String2",
(2,2) : "String3",
(3,15) :"String4",
(16,16) : "String5"};

def ValueInDict(value):
for i,j in int_dict.items():
if value >= i[0]:
if value <= i[1]:
print(j)
return
print("NOT THERE")

ValueInDict(5)

ouput :

 String4

I need a way to map multiple keys to the same value in a dictionary

As many of the comments have already pointed out, you seem to have your key/value structure inverted. I would recommend factoring out your int values as keys instead. This way you achieve efficient dictionary look ups using the int value as a key, and implement more elegant simple design in your data - using a dictionary as intended.

Ex: {9: ('1 2', '2 1'), 2: ('1 1',), 1729: ('9 10', '1 12')}

That being said the snippet below will do what you require. It first maps the data as shown above, then inverts the key/values essentially.

tel = {}
tel['1 12'] = 1729
tel['9 10'] = 1729
tel['1 2'] = 9
tel['2 1'] = 9
tel['1 1'] = 2
#-----------------------------------------------------------
from collections import defaultdict

new_tel = defaultdict(list)
for key, value in tel.items():
new_tel[value].append(key)

# new_tel -> {9: ['1 2', '2 1'], 2: ['1 1'], 1729: ['9 10', '1 12']}
print {tuple(key):value for value, key in new_tel.items()}
>>> {('1 2', '2 1'): 9, ('1 1',): 2, ('9 10', '1 12'): 1729}

Compact way to use alternative keys for same value in python dictionary

You can define the dict with keys of the same value grouped as a tuple first:

d = {('A', 'one'): 1, ('B', 'two'): 2}

so that you can then convert it to the desired dict with:

d = {key: value for keys, value in d.items() for key in keys}

d becomes:

{'A': 1, 'one': 1, 'B': 2, 'two': 2}

How to assign one value to multiple keys in a C# dictionary?

A Dictionary<TKey, TValue> is a collection of keys and values. In this collection, each key is mapped to just one value. And it has been implemented in the System.Collection.Generics namespace.

On the other hand, there is a collection named Lookup<TKey, TElement> which represents a one to many mapping between keys and values. I.e. it maps one key to one or more values, and it is in the System.Linq namespace.

You can convert any collections which have implemented the IEnumerable interface and the ToLookup() method in the System.Linq namespace to construct the Lookup<TKey, TElement> collection.

Read more about Lookup collection and Dictionary in the Microsoft tutorials about C# language.

In this question, we could consider a package consisting of two fields, the "Alphabet" character and its "Counts" in a sentence.

class Package
{
public char Alphabet;
public int Counts;
}

Then construct the Lookup data structure:

public static void LookupExample()
{
// Create a dictionary of Packages to put into a Lookup data structure.
var testDict = new Dictionary <char, int>() {
new Package { Alphabet = 'A', Counts = 1},
new Package { Alphabet = 'B', Counts = 3},
new Package { Alphabet = 'C', Counts = 3},
new Package { Alphabet = 'D', Counts = 2},
new Package { Alphabet = 'E', Counts = 1},
new Package { Alphabet = 'F', Counts = 4},
new Package { Alphabet = 'G', Counts = 2},
new Package { Alphabet = 'H', Counts = 4},
new Package { Alphabet = 'I', Counts = 1},
new Package { Alphabet = 'J', Counts = 8},
new Package { Alphabet = 'K', Counts = 5},
new Package { Alphabet = 'L', Counts = 1},
new Package { Alphabet = 'M', Counts = 3},
new Package { Alphabet = 'N', Counts = 1},
new Package { Alphabet = 'O', Counts = 1},
new Package { Alphabet = 'P', Counts = 3},
new Package { Alphabet = 'Q', Counts = 10},
new Package { Alphabet = 'R', Counts = 1},
new Package { Alphabet = 'S', Counts = 1},
new Package { Alphabet = 'T', Counts = 1},
new Package { Alphabet = 'U', Counts = 1},
new Package { Alphabet = 'V', Counts = 4},
new Package { Alphabet = 'W', Counts = 4},
new Package { Alphabet = 'X', Counts = 8},
new Package { Alphabet = 'Y', Counts = 4},
new Package { Alphabet = 'Z', Counts = 10}};


// Create a Lookup to organize the packages. Use the Counts of each Alphabet as the key value.
// Select Alpahbet appended to each Counts in the Lookup.
Lookup<int, char> lookup = (Lookup<int, char>)testDict.ToLookup(p => p.Counts, p => p.Alphabet);

// Iterate through each IGrouping in the Lookup and output the contents.
foreach (IGrouping<int, char> packageGroup in lookup)
{
// Print the key value of the IGrouping.
Console.WriteLine(packageGroup.Key);
// Iterate through each value in the IGrouping and print its value.
foreach (char chr in packageGroup)
Console.WriteLine(" {0}", Convert.ToString(chr));
}
}

This helps to consider the "Counts" as the new key and assign multiple "Alphabet" characters to it which have same amount for their "Counts" value!

Multiple assignments into a python dictionary

You can use dict.update:

d.update({'a': 10, 'c': 200, 'c': 30})

This will overwrite the values for existing keys and add new key-value-pairs for keys that do not already exist.

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.



Related Topics



Leave a reply



Submit