Get an arbitrary key/item from a map

get list of keys in map golang
go get list of keys from map
golang map
golang map get first item
list of keys from map golang
golang get first element of slice
return map keys golang
get index from map golang

I am new to Go and now I want to get an arbitrary item from a map; what's the idiomatic way to do that? I can only think of something like this:

func get_some_key(m map[int]int) int {
    for k := range m {
        return k
    }
    return 0
}

The reason I want that is I am using a map to maintain a set of jobs, and with a map I can get a pending job or remove a finished job in O(1). I guess this should be a common requirement but it's not obvious how to do it in Go.

Whether getting an arbitrary key from a hash table is a common requirement may be discussed. Other language map implementations often lack this feature (eg. Dictionary in C# )

However, your solution is probably the fastest one, but you will be left with a pseudo-random algorithm that you do not control. And while the current implementation uses a pseudo-random algorithm, the Go Specification doesn't give you any assurance it will actually be random, only that it is not guaranteed to be predictable:

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.

If you want more control of the randomization, you can also in parallel keep an updated slice of values (or keys) contained in the map, using the randomization of your choice (math/rand or crypto/rand for more extreme cases) to get the value stored at an index, selected randomly, in the slice.

Java: How to Get Random Key-Value Element From HashMap , Java: How to Get Random Key-Value Element From HashMap. Last Updated on Entry<String, String>> list = new ArrayList<Map.Entry<String� An associative array, where arbitrary keys are mapped to values. The keys can be any object with __hash__() and __eq__() methods. There are a couple points to keep in mind: Dictionaries map keys to values and store them in an array or collection.

Here is a more generic version, although it may be less efficient:

    keys := reflect.ValueOf(mapI).MapKeys()
    return keys[rand.Intn(len(keys))].Interface()

https://play.golang.org/p/0uvpJ0diG4e

Object.keys, values, entries, In the previous chapter we saw methods map.keys() , map.values() , map.entries () . The first difference is that we have to call Object.keys(obj) , and not obj.keys () There is a salaries object with arbitrary number of salaries. Then I mapped over the arbitrary record and constructed a new dictionary with properties that have the appropriate keys. So, if dict(k: Arbitrary<String>, v: Arbitrary<A>): Arbitrary<Map<A>> gives me that same kind of functionality, which I think it does (I'm a little new to this, that's why I hesitate to say for sure), then yes!

As a "global" solution, as I am a big fan of elasticsearch, you could use another map/array to store your data, to build a kind of an inverted dictionary.

Keyed collections, A Map object is a simple key/value map and can iterate its elements in insertion order. Traditionally, objects have been used to map strings to values. which the keys are objects only and the values can be arbitrary values. Returns a map iterator Iterator that can be used by maps:next/1 to traverse the key-value associations in a map. When iterating over a map, the memory usage is guaranteed to be bounded no matter the size of the map.

Map (Groovy JDK enhancements), Looks up an item in a Map for the given key and returns the value - unless there If your Map doesn't support null keys or values, you might get a runtime error, e.g. If more than one entry has the maximum value, an arbitrary choice is made � Unlike QHash, which stores its items in an arbitrary order, QMap stores its items ordered by key. Items that share the same key (because the map is a QMultiMap) will appear consecutively, from the most recently to the least recently inserted value.

IdentityHashMap (Java Platform SE 7 ), This class provides constant-time performance for the basic operations (get and rather than risking arbitrary, non-deterministic behavior at an undetermined Tests whether the specified object reference is a key in this identity hash map. ''' def filterTheDict(dictObj, callback): newDict = dict() # Iterate over all the items in dictionary for (key, value) in dictObj.items(): # Check if item satisfies the given condition then add to new dict if callback((key, value)): newDict[key] = value return newDict This function accepts,

Arrays, Slices and Maps in Go, An element value can be accessed or modified through its associated key. But maps have two advantages over arrays and slices: T is an arbitrary type. Writes a key/value pair to a key value map, whether the key value map is encrypted or unencrypted. If the key value map specified in the mapIdentifier attribute on the parent element doesn't exist, the map is automatically created (as unencrypted). If the key value map already exists, the key/value are added to it.

Comments
  • Do you know the value of the key you are trying to get or set or are you trying to find a random key or some key you don't know in advance?
  • Are you looking for the key that has a particular value? If you're just looking for the value associated with a key it's simply m[i].
  • Your approach looks good. If the map can be concurrently accessed by two goroutines, guard the retrieve/delete operation with a sync.Mutex so two goroutines don't grab the same job (and because maps are, for speed's sake, not natively thread-safe).
  • @dethtron5000 I don't need random key or sth, I just need to give me a key for any element in the map if there are any
  • @twotwotwo Yep, I saw that from the maps in action article, and to be clear, I am using a sync.RWMutex.
  • Thanks for your answer, please see my comment above, I don't need any control of randomization, I just want a way that "just give me an element from the map" if there are any.
  • @chuchao333 Then your solution is good. Another similar way is var k, v int; for k, v = range m { break } if you want to do it inline. And to make sure you got a value, you can do: var k, v int; var ok bool; for k, v = range m { ok = true; break }
  • What do you mean by "get an index from the slice" in your last sentence?
  • @jochen: Maybe poor choice of words. I mean getting the value stored at a specific index in a slice. Eg.: slice[rand.Intn(len(slice))]
  • @ANisus: But the question was about maps, not slices? And I can't see an easy way to get a slice of all keys or similar.
  • It runs about 5 times slower than the method Xeoncross suggested. (Although I like this version because it's much simpler.) I made a test code here: play.golang.org/p/L2z5kGJ7WsW
  • This is even more terrible! It's O(N) runtime and memory!